ویکیپدیا:درخواستهای ربات/افزودن الگو ناوباکس به مقالات: تفاوت میان نسخهها
Appearance
محتوای حذفشده محتوای افزودهشده
جز Bot: Replace deprecated <source> tag and "enclose" parameter [https://lists.wikimedia.org/pipermail/wikitech-ambassadors/2020-April/002284.html] |
بدون خلاصۀ ویرایش |
||
خط ۳۲: | خط ۳۲: | ||
# Reza (User:reza1615) |
# Reza (User:reza1615) |
||
# -*- coding: utf-8 -*- |
# -*- coding: utf-8 -*- |
||
import |
import pywikibot, json, sys, re |
||
from pywikibot import pagegenerators |
|||
⚫ | |||
wikipedia.config.put_throttle = 0 |
|||
wikipedia.put_throttle.setDelay() |
|||
⚫ | |||
_cache={} |
_cache={} |
||
botversion= |
botversion='1706' |
||
boxes=[ |
boxes=['infobox','Geobox','Taxobo', 'جعبه'] |
||
def solve_redirect(tem,fapage,fapage_redi,delink): |
def solve_redirect(tem,fapage,fapage_redi,delink): |
||
tem = |
tem = pywikibot.Page(fasite,tem.title()) |
||
try: |
try: |
||
text=tem.get() |
text=tem.get() |
||
text=text.replace( |
text=text.replace('[[ ','[[').replace(' ]]',']]').replace(' |','|').replace('[['+fapage.title()+']]','[['+fapage_redi.title()+'|'+fapage.title()+']]') |
||
text=text.replace( |
text=text.replace('[['+fapage.title()+'|','[['+fapage_redi.title()+'|') |
||
tem.put(text, |
tem.put(text,'ربات:اصلاح تغییرمسیر') |
||
#wikipedia.output(u'\03{lightyellow}اصلاح تغیرمسیر درون الگو\03{default}') |
|||
except: |
except: |
||
pass |
pass |
||
def link_filtering(tem_text,links): |
def link_filtering(tem_text,links): |
||
mytext= |
mytext='\n' |
||
tem_text_f=tem_text.replace( |
tem_text_f=tem_text.replace('\r','') |
||
tem_text_f=tem_text_f.replace( |
tem_text_f=tem_text_f.replace('\n*',' ') |
||
tem_text_f=tem_text_f.replace( |
tem_text_f=tem_text_f.replace(' |','|').replace(' |','|').replace(' |','|').replace(' |','|') |
||
tem_text_f=tem_text_f.replace( |
tem_text_f=tem_text_f.replace(' =','=').replace(' =','=').replace(' =','=').replace(' =','=') |
||
#wikipedia.output(tem_text_f) |
|||
our_test_text=re.sub( |
our_test_text=re.sub(r'\{\{ *[Nn]ational.*?squad','',tem_text_f) |
||
if our_test_text!=tem_text_f: |
if our_test_text!=tem_text_f: |
||
for i in tem_text_f.split( |
for i in tem_text_f.split('\n|'): |
||
if |
if 'p1' not in i and 'p2' not in i and 'p3' not in i and 'p4' not in i and 'p5' not in i and 'p6' not in i and 'p7' not in i and 'p8' not in i and 'p9' not in i and 'p0' not in i and 'coach' not in i: |
||
mytext+=i |
mytext+=i |
||
elif tem_text_f!=re.sub( |
elif tem_text_f!=re.sub(r'\{\{ *[nN]avbox with columns','',tem_text_f): |
||
for i in tem_text_f.split( |
for i in tem_text_f.split('\n|'): |
||
if re.sub( |
if re.sub(r'^ *col\d{1,2} *\=','',i)==i: |
||
mytext+=i |
mytext+=i |
||
elif tem_text_f!=re.sub( |
elif tem_text_f!=re.sub(r'\{\{ *[Yy]ear [Nn]obel [pP]rize [Ww]inners','',tem_text_f): |
||
for i in tem_text_f.split( |
for i in tem_text_f.split('\n|'): |
||
if re.sub( |
if re.sub(r'(chemistry|physics|medicine|economy|literature|peace)','',i)==i: |
||
mytext+=i |
mytext+=i |
||
elif tem_text_f!=re.sub( |
elif tem_text_f!=re.sub(r'\{\{ *([Cc]ounty|جستارهای کشور)','',tem_text_f): |
||
for i in tem_text_f.split( |
for i in tem_text_f.split('\n|'): |
||
if re.sub( |
if re.sub(r'^ *(cr|md|ua|bd|ct|rv|cl|history|geography|politics|military|economy|society|culture|symbols) *\=','',i)==i: |
||
⚫ | |||
⚫ | |||
⚫ | |||
if i.find(u'body1')==-1 and i.find(u'body2')==-1 and i.find(u'body3')==-1 and i.find(u'body4')==-1 and i.find(u'body5')==-1 and i.find(u'body6')==-1 and i.find(u'body7')==-1 and i.find(u'body8')==-1: |
|||
⚫ | |||
mytext+=i |
mytext+=i |
||
⚫ | |||
⚫ | |||
⚫ | |||
if 'body{}'.format(i) not in i: |
|||
⚫ | |||
else: |
else: |
||
list_ = ['list ', 'list=', 'list1', 'list2', 'list3', 'list4', 'list5', 'list6', 'list7', 'list8', 'list9', 'list0', 'فهرست۰', 'فهرست۹', 'فهرست۸', 'فهرست۷', 'فهرست۶', 'فهرست۵', 'فهرست۴', 'فهرست۳', 'فهرست۲', 'فهرست۱', 'content1', 'content2', 'content3', 'content4', 'content5', 'content6', 'content7', 'content8', 'content9', 'content0'] |
|||
⚫ | |||
for i in tem_text_f.split('\n|'): |
|||
if i.find(u'list ')==-1 and i.find(u'list=')==-1 and i.find(u'list1')==-1 and i.find(u'list2')==-1 and i.find(u'list3')==-1 and i.find(u'list4')==-1 and i.find(u'list5')==-1 and i.find(u'list6')==-1 and i.find(u'list7')==-1 and i.find(u'list8')==-1 and i.find(u'list9')==-1 and i.find(u'list0')==-1 and i.find(u'فهرست۰')==-1 and i.find(u'فهرست۹')==-1 and i.find(u'فهرست۸')==-1 and i.find(u'فهرست۷')==-1 and i.find(u'فهرست۶')==-1 and i.find(u'فهرست۵')==-1 and i.find(u'فهرست۴')==-1 and i.find(u'فهرست۳')==-1 and i.find(u'فهرست۲')==-1 and i.find(u'فهرست۱')==-1 and i.find(u'content1')==-1 and i.find(u'content2')==-1 and i.find(u'content3')==-1 and i.find(u'content4')==-1 and i.find(u'content5')==-1 and i.find(u'content6')==-1 and i.find(u'content7')==-1 and i.find(u'content8')==-1 and i.find(u'content9')==-1 and i.find(u'content0')==-1: |
|||
for j in list_: |
|||
if j not in i: |
|||
⚫ | |||
black_text= |
black_text=' ' |
||
dict={ |
dict={'<noinclude>':'</noinclude>','{{یادکرد':'}}','<ref':'</ref','{{cite':'}}','{{Cite':'}}'} |
||
for a in dict: |
for a in dict: |
||
count=0 |
count=0 |
||
خط ۹۹: | خط ۹۸: | ||
if count>1: |
if count>1: |
||
black_text+=i.split(dict[a])[0] |
black_text+=i.split(dict[a])[0] |
||
black_links2 = re.findall( |
black_links2 = re.findall(r'\[\[(.*?)(?:\||\]\])',black_text+mytext, re.S) |
||
#black_links2=[] |
|||
#for i in black_links: |
|||
# black_links2.append(i.replace(u']]',u'').replace(u'[[',u'').strip().split(u'|')[0]) |
|||
new_links,delink=[],[] |
new_links,delink=[],[] |
||
for i in links: |
for i in links: |
||
itest=i.split( |
itest=i.split('|')[0].replace('_',' ').replace(' ',' ') |
||
if not itest.strip(): |
if not itest.strip(): |
||
delink.append(i) |
delink.append(i) |
||
if itest in black_links2 or itest in new_links or |
if itest in black_links2 or itest in new_links or ':' in i: |
||
continue |
continue |
||
else: |
else: |
||
if itest== |
if itest=='آذرشهر': |
||
new_links.append(i) |
new_links.append(i) |
||
continue |
continue |
||
itest=itest.strip() |
itest=itest.strip() |
||
itest=re.sub( |
itest=re.sub(r'[۱۲۳۴۵۶۷۸۹۰]','',itest) |
||
itest=re.sub( |
itest=re.sub(r'\((میلادی|قمری|پیش از میلاد|قبل از میلاد)\)','',itest) |
||
b_list=[ |
b_list=['کاپیتان (فوتبال)','استان','دهستان','کشور','شهر','شهرستان','بخش','فروردین','اردیبهشت','خرداد', |
||
'تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند','ژانویه','فوریه','مارس','ژوئیه','ژوئن', |
|||
'آوریل','اوت','سپتامبر','نوامبر','دسامبر','می','اکتبر'] |
|||
itest=re.sub( |
itest=re.sub(r'('+'|'.join(b_list).replace(')','\)').replace('(','\(')+')','',itest) |
||
if not itest.strip(): |
if not itest.strip(): |
||
delink.append(i) |
delink.append(i) |
||
continue |
continue |
||
itest=re.sub( |
itest=re.sub(r'[^صثقفغعهخحجچشسیبلاتنمکگظطزرذدپوژآيئؤًٌٍَُِّْٔ]','',itest) |
||
if not itest.strip(): |
if not itest.strip(): |
||
continue |
continue |
||
new_links.append(i) |
new_links.append(i) |
||
#for i in new_links: |
|||
# wikipedia.output(i) |
|||
return new_links,delink |
return new_links,delink |
||
def boxfind(text_en): |
def boxfind(text_en): |
||
text_en=text_en.replace( |
text_en=text_en.replace('{{ ','{{').replace('{{ ','{{').replace('{{template:','{{').replace('{{Template:','{{').replace('\r','') |
||
start=False |
start=False |
||
box= |
box='\n' |
||
diff=1 |
diff=1 |
||
linebaz,linebasteh=0,0 |
linebaz,linebasteh=0,0 |
||
خط ۱۴۲: | خط ۱۳۶: | ||
up_our_box=our_box[0].upper()+our_box[1:] |
up_our_box=our_box[0].upper()+our_box[1:] |
||
lower_our_box=our_box[0].lower()+our_box[1:] |
lower_our_box=our_box[0].lower()+our_box[1:] |
||
regex_result=re.findall( |
regex_result=re.findall('(\{\|([\n\s]+|)\{\{([\s]+|)'+our_box+')',text_en, re.IGNORECASE) |
||
if regex_result: |
if regex_result: |
||
if regex_result[0][0].strip(): |
if regex_result[0][0].strip(): |
||
pre_template= |
pre_template='{|' |
||
post_tempate= |
post_tempate='|}' |
||
text_en=text_en.replace( |
text_en=text_en.replace('{| ','{|').replace('{| ','{|').replace('{|\n','{|').replace('{|\n','{|') |
||
text_en=text_en.replace( |
text_en=text_en.replace(' |}','|}').replace(' |}','|}').replace('\n|}','|}').replace('\n|}','|}') |
||
else: |
else: |
||
pre_template,post_tempate= |
pre_template,post_tempate='','' |
||
lines=text_en.split('\n') |
lines=text_en.split('\n') |
||
for line in lines: |
for line in lines: |
||
if line== |
if line=='': |
||
continue |
continue |
||
if line.find(pre_template+ |
if line.find(pre_template+'{{'+lower_our_box)!=-1 :# lower case |
||
start=True |
start=True |
||
linebaz,linebasteh=0,0 |
linebaz,linebasteh=0,0 |
||
box+=pre_template+ |
box+=pre_template+'{{'+lower_our_box+line.split(pre_template+'{{'+lower_our_box)[1]+'\n' |
||
linebaz += |
linebaz += line.count( pre_template+"{{" ) |
||
linebasteh += |
linebasteh += line.count( "}}"+post_tempate ) |
||
diff=linebaz-linebasteh |
diff=linebaz-linebasteh |
||
continue |
continue |
||
if line.find(pre_template+ |
if line.find(pre_template+'{{'+up_our_box)!=-1 :# upper case |
||
start=True |
start=True |
||
linebaz,linebasteh=0,0 |
linebaz,linebasteh=0,0 |
||
box+=pre_template+ |
box+=pre_template+'{{'+up_our_box+line.split(pre_template+'{{'+up_our_box)[1]+'\n' |
||
linebaz += |
linebaz += line.count( pre_template+"{{" ) |
||
linebasteh += |
linebasteh += line.count( "}}" +post_tempate) |
||
diff=linebaz-linebasteh |
diff=linebaz-linebasteh |
||
continue |
continue |
||
if start==True and diff!=0: |
if start==True and diff!=0: |
||
linebaz += |
linebaz += line.count( pre_template+"{{" ) |
||
linebasteh += |
linebasteh += line.count( "}}"+post_tempate ) |
||
diff=linebaz-linebasteh |
diff=linebaz-linebasteh |
||
box+=line+'\n' |
box+=line+'\n' |
||
خط ۱۸۰: | خط ۱۷۴: | ||
if box.strip(): |
if box.strip(): |
||
break |
break |
||
return box.replace( |
return box.replace('}}|}','}}\n|}') |
||
def Get_box (txt): |
def Get_box (txt): |
||
خط ۱۸۶: | خط ۱۸۰: | ||
if my_box.strip(): |
if my_box.strip(): |
||
return my_box.strip() |
return my_box.strip() |
||
txt=txt.replace( |
txt=txt.replace('\r','') |
||
lines=txt.split('\n') |
lines=txt.split('\n') |
||
matn=' ' |
matn=' ' |
||
for line in lines: |
for line in lines: |
||
linebaz= |
linebaz=line.count(line,'{{') |
||
linebaste= |
linebaste=line.count(line,'}}') |
||
diff=linebaz-linebaste |
diff=linebaz-linebaste |
||
if diff==0: |
if diff==0: |
||
خط ۱۹۷: | خط ۱۹۱: | ||
linebaz=0 |
linebaz=0 |
||
linebaste=0 |
linebaste=0 |
||
matn+=line+ |
matn+=line+'\n' |
||
my_box='' |
my_box='' |
||
for our_box in boxes: |
for our_box in boxes: |
||
our_box=our_box.strip() |
our_box=our_box.strip() |
||
try: |
try: |
||
my_box= re.search( |
my_box= re.search(r'(\{\{\s*['+our_box[0].lower()+our_box[0].upper()+r']'+our_box[1:]+r'[_\s](?:\{\{.*?\}\}|[^\}])*\}\})',matn, re.S).group(1)# if Template box has other name please chang this regex |
||
my_box=my_box.replace( |
my_box=my_box.replace('$AAAA$','{{').replace('!BBBB!','}}') |
||
break |
break |
||
except: |
except: |
||
خط ۲۱۲: | خط ۲۰۶: | ||
def addtext (fapage,text,addtemplate,addtemplate2,msg_clean,username_r,tempetype): |
def addtext (fapage,text,addtemplate,addtemplate2,msg_clean,username_r,tempetype): |
||
text_t=text.replace( |
text_t=text.replace('_',' ') |
||
if |
if '{{ابهامزدایی' in text_t or '{{نمایه' in text_t or '{{نام کوچک' in text_t or '{{نام خانوادگی' in text_t or '{{مقالات مجموعهنمایه' in text_t: |
||
return False |
return False |
||
text=text.replace(addtemplate+ |
text=text.replace(addtemplate+'\n','') |
||
if tempetype=='navbox': |
if tempetype=='navbox': |
||
if |
if 'رده:' in text: |
||
num=text.find( |
num=text.find('[[رده:') |
||
text=text[:num]+addtemplate+ |
text=text[:num]+addtemplate+'\n'+text[num:] |
||
else: |
else: |
||
text+= |
text+='\n'+addtemplate |
||
elif tempetype=='sidebar': |
elif tempetype=='sidebar': |
||
ourbox=Get_box (text) |
ourbox=Get_box (text) |
||
if not ourbox: |
if not ourbox: |
||
text=addtemplate+ |
text=addtemplate+'\n'+text |
||
my_text_result=re.findall( |
my_text_result=re.findall(r'\{\{(?:ویکی[ ]?سازی|منبع|بدون منبع|لحن|تمیزکاری|طفرهآمیز|نامفهوم|تبلیغات|بهبود منبع|طرفداری|درستی|ادغام با|ادغام از|ادغام|در دست ویرایش ۲|تازه درگذشته|اصلاح ترجمه|رده-نیاز)(?:.*?)?\}\}',text, re.IGNORECASE) |
||
if my_text_result: |
if my_text_result: |
||
for i in my_text_result: |
for i in my_text_result: |
||
text=i+ |
text=i+'\n'+text.replace(i+'\n','').replace(i,'') |
||
else: |
else: |
||
return False |
return False |
||
خط ۲۳۵: | خط ۲۲۹: | ||
return False |
return False |
||
text,cleaning_version,msg_clean2=fa_cosmetic_changes.fa_cosmetic_changes(text,fapage) |
|||
try: |
try: |
||
fapage.put(text, |
fapage.put(text,'[[وپ:ابزارک|افزودن ناوباکس]] '+botversion+'> '+addtemplate2+' (درخواست [['+username_r+']])'+msg_clean) |
||
#wikipedia.output(u'\03{lightred}++++'+fapage.title()+u'\03{default}') |
|||
return True |
return True |
||
except: |
except: |
||
خط ۲۴۷: | خط ۲۴۰: | ||
temps=[] |
temps=[] |
||
try: |
try: |
||
enlink= |
enlink=str(enlink).replace('[[','').replace(']]','').replace('en:','').replace('fa:','') |
||
except: |
except: |
||
enlink=enlink.replace( |
enlink=enlink.replace('[[','').replace(']]','').replace('en:','').replace('fa:','') |
||
enlink=enlink.split( |
enlink=enlink.split('#')[0].strip() |
||
enlink=enlink.replace( |
enlink=enlink.replace(' ','_') |
||
if _cache.get(tuple([enlink, 'templatequery'])): |
if _cache.get(tuple([enlink, 'templatequery'])): |
||
return _cache[tuple([enlink, 'templatequery'])] |
return _cache[tuple([enlink, 'templatequery'])] |
||
if enlink== |
if enlink=='': |
||
_cache[tuple([enlink, 'templatequery'])]=False |
_cache[tuple([enlink, 'templatequery'])]=False |
||
return False |
return False |
||
خط ۲۶۷: | خط ۲۶۰: | ||
try: |
try: |
||
categoryname = |
categoryname = pywikibot.data.api.Request( |
||
site=fasite, parameters=params) |
|||
⚫ | |||
categoryname = categoryname.submit() |
|||
⚫ | |||
templateha=categoryname['query']['pages'][item]['templates'] |
|||
break |
break |
||
for temp in templateha: |
for temp in templateha: |
||
temps.append(temp[ |
temps.append(temp['title'].replace('_',' ').replace('الگو:','').replace('template:','').strip()) |
||
_cache[tuple([enlink, 'templatequery'])]=temps |
_cache[tuple([enlink, 'templatequery'])]=temps |
||
return temps |
return temps |
||
خط ۲۸۱: | خط ۲۷۶: | ||
def check_user_edits(username): |
def check_user_edits(username): |
||
username=username.replace( |
username=username.replace(' ','_') |
||
if _cache.get(tuple([username, 'check_user_edits'])): |
if _cache.get(tuple([username, 'check_user_edits'])): |
||
return _cache[tuple([username, 'check_user_edits'])] |
return _cache[tuple([username, 'check_user_edits'])] |
||
خط ۲۹۱: | خط ۲۸۶: | ||
} |
} |
||
try: |
try: |
||
usernamequery = |
usernamequery = pywikibot.data.api.Request( |
||
site=fasite, parameters=params) |
|||
⚫ | |||
usernamequery = usernamequery.submit() |
|||
⚫ | |||
_cache[tuple([username, 'check_user_edits'])]=True |
_cache[tuple([username, 'check_user_edits'])]=True |
||
return True |
return True |
||
خط ۳۱۷: | خط ۳۱۴: | ||
def add_nav(preloadingGen,username_r): |
def add_nav(preloadingGen,username_r): |
||
for tem in preloadingGen: |
for tem in preloadingGen: |
||
⚫ | |||
#user_pass,First_user=check_user(tem) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
#passport=True |
|||
enchar=u'qwertyuiopasdfghjklzxcvbnm' |
|||
⚫ | |||
⚫ | |||
continue |
continue |
||
if |
if '/' in tem_title or '\\' in tem_title: |
||
continue |
continue |
||
try: |
try: |
||
خط ۳۳۱: | خط ۳۲۳: | ||
except: |
except: |
||
continue |
continue |
||
tem_text=tem_text.replace( |
tem_text=tem_text.replace('{{ ','{{').replace('{{ ','{{').replace('{{الگو:','{{').replace('{{Template:','{{').replace('{{template:','{{') |
||
TempTemplates=templatequery(tem.title()) |
TempTemplates=templatequery(tem.title()) |
||
⚫ | |||
⚫ | |||
if not |
if not 'Navbox' in TempTemplates and not 'نوار جانبی' in TempTemplates: |
||
continue |
continue |
||
if |
if 'Navbox' in TempTemplates: |
||
tempetype= |
tempetype='navbox' |
||
if |
if 'نوار جانبی' in TempTemplates: |
||
tempetype= |
tempetype='sidebar' |
||
added_template=tem.title().replace( |
added_template=tem.title().replace('الگو:','').replace('template:','').replace('Template:','') |
||
if tem.namespace()!=10: |
if tem.namespace()!=10: |
||
continue |
continue |
||
خط ۳۴۷: | خط ۳۴۱: | ||
redirect_list=[] |
redirect_list=[] |
||
for i in redirects: |
for i in redirects: |
||
redirect_list.append(i.title().replace( |
redirect_list.append(i.title().replace('الگو:','').replace('template:','').replace('Template:','')) |
||
links=tem.linkedPages() |
links=tem.linkedPages() |
||
link_t=[] |
link_t=[] |
||
خط ۳۵۸: | خط ۳۵۲: | ||
links=[x for x in link_t if x not in link_t2] |
links=[x for x in link_t if x not in link_t2] |
||
links,delink=link_filtering(tem_text,links) |
links,delink=link_filtering(tem_text,links) |
||
#wikipedia.output(u'-----------------------------------------') |
|||
old_tem_text=tem_text |
old_tem_text=tem_text |
||
for nonlink in delink: |
for nonlink in delink: |
||
tem_text=tem_text.replace( |
tem_text=tem_text.replace('[['+nonlink+']]',nonlink.split('|')[0]) |
||
if old_tem_text!=tem_text: |
if old_tem_text!=tem_text: |
||
⚫ | |||
#wikipedia.output(u'\03{lightred}delinking\03{default}') |
|||
⚫ | |||
added_links=[] |
added_links=[] |
||
for faTitle in links: |
for faTitle in links: |
||
try: |
try: |
||
fapage= |
fapage=pywikibot.Page(fasite, faTitle) |
||
text=fapage.get() |
text=fapage.get() |
||
except |
except pywikibot.exceptions.IsRedirectPageError: |
||
fapage_redi = fapage.getRedirectTarget() |
fapage_redi = fapage.getRedirectTarget() |
||
try: |
try: |
||
خط ۳۸۰: | خط ۳۷۳: | ||
continue |
continue |
||
except: |
except: |
||
continue |
continue |
||
#wikipedia.output(u'\03{lightblue}--'+fapage.title()+u'---------\03{default}') |
|||
⚫ | |||
text,cleaning_version,msg_clean=fa_cosmetic_changes.fa_cosmetic_changes(text,fapage,msg) |
|||
old_text=text |
old_text=text |
||
for i in redirect_list: |
for i in redirect_list: |
||
text=text.replace( |
text=text.replace('{{'+i+'}}','{{'+added_template+'}}').replace('{{'+i+'|','{{'+added_template+'|') |
||
fatemplates=templatequery(fapage.title()) |
fatemplates=templatequery(fapage.title()) |
||
text=text.replace( |
text=text.replace('{{ ','{{').replace(' }}','}}').replace('{{الگو:','{{').strip() |
||
if not fatemplates: |
if not fatemplates: |
||
continue |
continue |
||
if |
if '{{'+added_template+'}}' not in text and (not added_template in fatemplates): |
||
addtemplate2= |
addtemplate2='[[الگو:'+added_template+']]' |
||
addtemplate= |
addtemplate='{{'+added_template+'}}' |
||
addtext_result= addtext (fapage,text,addtemplate,addtemplate2, |
addtext_result= addtext (fapage,text,addtemplate,addtemplate2,' ',username_r,tempetype) |
||
if addtext_result: |
if addtext_result: |
||
added_links.append(faTitle) |
added_links.append(faTitle) |
||
⚫ | |||
#wikipedia.output(u'added= {{\03{lightpurple}'+added_template+u'\03{default}}}') |
|||
continue |
continue |
||
if old_text!=text: |
if old_text!=text: |
||
try: |
try: |
||
fapage.put(text, |
fapage.put(text,'ربات:اصلاح تغییرمسیر ناوباکس') |
||
#wikipedia.output(u'\03{lightpurple}ربات:اصلاح تغییرمسیر ناوباکس\03{default}') |
|||
except: |
except: |
||
pass |
pass |
||
خط ۴۱۱: | خط ۴۰۰: | ||
my_result={} |
my_result={} |
||
if added_links: |
if added_links: |
||
my_result['msg']= |
my_result['msg']='الگو به «'+'»، «'.join(added_links)+'» افزوده شده!' |
||
else: |
else: |
||
my_result['msg']= |
my_result['msg']='الگو در همهٔ مقالات موجود است!' |
||
print |
print(json.dumps(my_result, ensure_ascii=False)) |
||
def main(): |
def main(): |
||
gen = None |
gen = None |
||
username_r= |
username_r='User:Yamaha5' |
||
genFactory = pagegenerators.GeneratorFactory() |
genFactory = pagegenerators.GeneratorFactory() |
||
for arg in |
for arg in sys.argv: |
||
if arg.startswith('-newtem'): |
if arg.startswith('-newtem'): |
||
arg=arg.replace(':','') |
arg=arg.replace(':','') |
||
if len(arg) == 7: |
if len(arg) == 7: |
||
genfa = pagegenerators.NewpagesPageGenerator( |
genfa = pagegenerators.NewpagesPageGenerator(site=fasite, total=100, namespaces=(10)) |
||
else: |
else: |
||
genfa = pagegenerators.NewpagesPageGenerator(int(arg[8:]), |
genfa = pagegenerators.NewpagesPageGenerator(site=fasite, total=int(arg[8:]), namespaces=(10)) |
||
gen = |
gen = genfa |
||
else: |
else: |
||
gen = genFactory. |
gen = genFactory.handle_arg( arg ) |
||
if not gen: |
if not gen: |
||
wikipedia.stopme() |
|||
sys.exit() |
sys.exit() |
||
⚫ | |||
preloadingGen = pagegenerators.PreloadingGenerator(gen,pageNumber = 60) |
|||
#preloadingGen = pagegenerators.NamespaceFilterPageGenerator(gen,10) |
|||
add_nav(preloadingGen,username_r) |
|||
خط ۴۴۲: | خط ۴۲۸: | ||
main() |
main() |
||
else: |
else: |
||
faPage = pywikibot.Page(fasite, sys.argv[1]) |
|||
add_nav([faPage],sys.argv[2]) |
|||
faPage = pywikibot.Page(fasite, faTitle) |
|||
⚫ | |||
</syntaxhighlight> |
</syntaxhighlight> |
نسخهٔ ۲۳ آوریل ۲۰۲۳، ساعت ۱۳:۳۲
این ربات برای افزودن الگوی ناوباکس به مقالاتی است که درون ناوباکس پیوند دارند.
آرگومانها
این ربات با همه آرگومانهای استاندارد پای ویکیپدیا کار می کند مانند
- -start:template:!
- -newtem:100
- -file:text.txt
نمونه دستور
این دستور به ۱۰۰ الگوی جدید ایجاد شده در صورتی که ناوباکس باشند مراجعه میکند و به مقالاتشان آن ناوباکسها را می افزاید
python navebox.py -newtem:100
نمونه ۲
این دستور به مقالات موجود در ناوباکسهای فهرست شده در یک فایل متنی الگو ناوباکس می افزاید.
همه الگوها را به صورت زیر
[[الگو:تست]] [[الگو:تست۱]] [[الگو:تست۲]] [[الگو:تست۳]]
در فایل text.txt ذخیره کنید
python navebox.py -file:text.txt
نکته
برای جلوگیری از خرابکاری در مقالات و نیافزودن ناوباکسهای اشتباه، این ربات فقط ناوباکسهایی که توسط کاربران بالای ۱۰۰۰ ویرایش ساخته میشود را میافزاید.
کد
#!/usr/bin/python
# Reza (User:reza1615)
# -*- coding: utf-8 -*-
import pywikibot, json, sys, re
from pywikibot import pagegenerators
fasite = pywikibot.Site('fa','wikipedia')
_cache={}
botversion='1706'
boxes=['infobox','Geobox','Taxobo', 'جعبه']
def solve_redirect(tem,fapage,fapage_redi,delink):
tem = pywikibot.Page(fasite,tem.title())
try:
text=tem.get()
text=text.replace('[[ ','[[').replace(' ]]',']]').replace(' |','|').replace('[['+fapage.title()+']]','[['+fapage_redi.title()+'|'+fapage.title()+']]')
text=text.replace('[['+fapage.title()+'|','[['+fapage_redi.title()+'|')
tem.put(text,'ربات:اصلاح تغییرمسیر')
except:
pass
def link_filtering(tem_text,links):
mytext='\n'
tem_text_f=tem_text.replace('\r','')
tem_text_f=tem_text_f.replace('\n*',' ')
tem_text_f=tem_text_f.replace(' |','|').replace(' |','|').replace(' |','|').replace(' |','|')
tem_text_f=tem_text_f.replace(' =','=').replace(' =','=').replace(' =','=').replace(' =','=')
our_test_text=re.sub(r'\{\{ *[Nn]ational.*?squad','',tem_text_f)
if our_test_text!=tem_text_f:
for i in tem_text_f.split('\n|'):
if 'p1' not in i and 'p2' not in i and 'p3' not in i and 'p4' not in i and 'p5' not in i and 'p6' not in i and 'p7' not in i and 'p8' not in i and 'p9' not in i and 'p0' not in i and 'coach' not in i:
mytext+=i
elif tem_text_f!=re.sub(r'\{\{ *[nN]avbox with columns','',tem_text_f):
for i in tem_text_f.split('\n|'):
if re.sub(r'^ *col\d{1,2} *\=','',i)==i:
mytext+=i
elif tem_text_f!=re.sub(r'\{\{ *[Yy]ear [Nn]obel [pP]rize [Ww]inners','',tem_text_f):
for i in tem_text_f.split('\n|'):
if re.sub(r'(chemistry|physics|medicine|economy|literature|peace)','',i)==i:
mytext+=i
elif tem_text_f!=re.sub(r'\{\{ *([Cc]ounty|جستارهای کشور)','',tem_text_f):
for i in tem_text_f.split('\n|'):
if re.sub(r'^ *(cr|md|ua|bd|ct|rv|cl|history|geography|politics|military|economy|society|culture|symbols) *\=','',i)==i:
mytext+=i
elif tem_text_f!=re.sub(r'\{\{ *([Uu]S state navigation box|[uU]S county navigation box)','',tem_text_f):
for i in tem_text_f.split('\n|'):
for i in range(1, 9):
if 'body{}'.format(i) not in i:
mytext+=i
else:
list_ = ['list ', 'list=', 'list1', 'list2', 'list3', 'list4', 'list5', 'list6', 'list7', 'list8', 'list9', 'list0', 'فهرست۰', 'فهرست۹', 'فهرست۸', 'فهرست۷', 'فهرست۶', 'فهرست۵', 'فهرست۴', 'فهرست۳', 'فهرست۲', 'فهرست۱', 'content1', 'content2', 'content3', 'content4', 'content5', 'content6', 'content7', 'content8', 'content9', 'content0']
for i in tem_text_f.split('\n|'):
for j in list_:
if j not in i:
mytext+=i
black_text=' '
dict={'<noinclude>':'</noinclude>','{{یادکرد':'}}','<ref':'</ref','{{cite':'}}','{{Cite':'}}'}
for a in dict:
count=0
for i in mytext.split(a):
count+=1
if count>1:
black_text+=i.split(dict[a])[0]
black_links2 = re.findall(r'\[\[(.*?)(?:\||\]\])',black_text+mytext, re.S)
new_links,delink=[],[]
for i in links:
itest=i.split('|')[0].replace('_',' ').replace(' ',' ')
if not itest.strip():
delink.append(i)
if itest in black_links2 or itest in new_links or ':' in i:
continue
else:
if itest=='آذرشهر':
new_links.append(i)
continue
itest=itest.strip()
itest=re.sub(r'[۱۲۳۴۵۶۷۸۹۰]','',itest)
itest=re.sub(r'\((میلادی|قمری|پیش از میلاد|قبل از میلاد)\)','',itest)
b_list=['کاپیتان (فوتبال)','استان','دهستان','کشور','شهر','شهرستان','بخش','فروردین','اردیبهشت','خرداد',
'تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند','ژانویه','فوریه','مارس','ژوئیه','ژوئن',
'آوریل','اوت','سپتامبر','نوامبر','دسامبر','می','اکتبر']
itest=re.sub(r'('+'|'.join(b_list).replace(')','\)').replace('(','\(')+')','',itest)
if not itest.strip():
delink.append(i)
continue
itest=re.sub(r'[^صثقفغعهخحجچشسیبلاتنمکگظطزرذدپوژآيئؤًٌٍَُِّْٔ]','',itest)
if not itest.strip():
continue
new_links.append(i)
return new_links,delink
def boxfind(text_en):
text_en=text_en.replace('{{ ','{{').replace('{{ ','{{').replace('{{template:','{{').replace('{{Template:','{{').replace('\r','')
start=False
box='\n'
diff=1
linebaz,linebasteh=0,0
for our_box in boxes:
our_box=our_box.strip()
up_our_box=our_box[0].upper()+our_box[1:]
lower_our_box=our_box[0].lower()+our_box[1:]
regex_result=re.findall('(\{\|([\n\s]+|)\{\{([\s]+|)'+our_box+')',text_en, re.IGNORECASE)
if regex_result:
if regex_result[0][0].strip():
pre_template='{|'
post_tempate='|}'
text_en=text_en.replace('{| ','{|').replace('{| ','{|').replace('{|\n','{|').replace('{|\n','{|')
text_en=text_en.replace(' |}','|}').replace(' |}','|}').replace('\n|}','|}').replace('\n|}','|}')
else:
pre_template,post_tempate='',''
lines=text_en.split('\n')
for line in lines:
if line=='':
continue
if line.find(pre_template+'{{'+lower_our_box)!=-1 :# lower case
start=True
linebaz,linebasteh=0,0
box+=pre_template+'{{'+lower_our_box+line.split(pre_template+'{{'+lower_our_box)[1]+'\n'
linebaz += line.count( pre_template+"{{" )
linebasteh += line.count( "}}"+post_tempate )
diff=linebaz-linebasteh
continue
if line.find(pre_template+'{{'+up_our_box)!=-1 :# upper case
start=True
linebaz,linebasteh=0,0
box+=pre_template+'{{'+up_our_box+line.split(pre_template+'{{'+up_our_box)[1]+'\n'
linebaz += line.count( pre_template+"{{" )
linebasteh += line.count( "}}" +post_tempate)
diff=linebaz-linebasteh
continue
if start==True and diff!=0:
linebaz += line.count( pre_template+"{{" )
linebasteh += line.count( "}}"+post_tempate )
diff=linebaz-linebasteh
box+=line+'\n'
if diff==0 and start==True:
break
if box.strip():
break
return box.replace('}}|}','}}\n|}')
def Get_box (txt):
my_box=boxfind(txt)
if my_box.strip():
return my_box.strip()
txt=txt.replace('\r','')
lines=txt.split('\n')
matn=' '
for line in lines:
linebaz=line.count(line,'{{')
linebaste=line.count(line,'}}')
diff=linebaz-linebaste
if diff==0:
line=line.replace('{{','$AAAA$').replace('}}','!BBBB!')
linebaz=0
linebaste=0
matn+=line+'\n'
my_box=''
for our_box in boxes:
our_box=our_box.strip()
try:
my_box= re.search(r'(\{\{\s*['+our_box[0].lower()+our_box[0].upper()+r']'+our_box[1:]+r'[_\s](?:\{\{.*?\}\}|[^\}])*\}\})',matn, re.S).group(1)# if Template box has other name please chang this regex
my_box=my_box.replace('$AAAA$','{{').replace('!BBBB!','}}')
break
except:
continue
if not my_box.strip():
return False
return my_box.strip()
def addtext (fapage,text,addtemplate,addtemplate2,msg_clean,username_r,tempetype):
text_t=text.replace('_',' ')
if '{{ابهامزدایی' in text_t or '{{نمایه' in text_t or '{{نام کوچک' in text_t or '{{نام خانوادگی' in text_t or '{{مقالات مجموعهنمایه' in text_t:
return False
text=text.replace(addtemplate+'\n','')
if tempetype=='navbox':
if 'رده:' in text:
num=text.find('[[رده:')
text=text[:num]+addtemplate+'\n'+text[num:]
else:
text+='\n'+addtemplate
elif tempetype=='sidebar':
ourbox=Get_box (text)
if not ourbox:
text=addtemplate+'\n'+text
my_text_result=re.findall(r'\{\{(?:ویکی[ ]?سازی|منبع|بدون منبع|لحن|تمیزکاری|طفرهآمیز|نامفهوم|تبلیغات|بهبود منبع|طرفداری|درستی|ادغام با|ادغام از|ادغام|در دست ویرایش ۲|تازه درگذشته|اصلاح ترجمه|رده-نیاز)(?:.*?)?\}\}',text, re.IGNORECASE)
if my_text_result:
for i in my_text_result:
text=i+'\n'+text.replace(i+'\n','').replace(i,'')
else:
return False
else:
return False
try:
fapage.put(text,'[[وپ:ابزارک|افزودن ناوباکس]] '+botversion+'> '+addtemplate2+' (درخواست [['+username_r+']])'+msg_clean)
return True
except:
pass
return False
def templatequery(enlink):
temps=[]
try:
enlink=str(enlink).replace('[[','').replace(']]','').replace('en:','').replace('fa:','')
except:
enlink=enlink.replace('[[','').replace(']]','').replace('en:','').replace('fa:','')
enlink=enlink.split('#')[0].strip()
enlink=enlink.replace(' ','_')
if _cache.get(tuple([enlink, 'templatequery'])):
return _cache[tuple([enlink, 'templatequery'])]
if enlink=='':
_cache[tuple([enlink, 'templatequery'])]=False
return False
params = {
'action': 'query',
'prop':'templates',
'titles': enlink,
'redirects': 1,
'tllimit':500,
}
try:
categoryname = pywikibot.data.api.Request(
site=fasite, parameters=params)
categoryname = categoryname.submit()
for item in categoryname['query']['pages']:
templateha=categoryname['query']['pages'][item]['templates']
break
for temp in templateha:
temps.append(temp['title'].replace('_',' ').replace('الگو:','').replace('template:','').strip())
_cache[tuple([enlink, 'templatequery'])]=temps
return temps
except:
_cache[tuple([enlink, 'templatequery'])]=False
return False
def check_user_edits(username):
username=username.replace(' ','_')
if _cache.get(tuple([username, 'check_user_edits'])):
return _cache[tuple([username, 'check_user_edits'])]
params = {
'action': 'query',
'list': 'users',
'ususers': username,
'usprop':'editcount'
}
try:
usernamequery = pywikibot.data.api.Request(
site=fasite, parameters=params)
usernamequery = usernamequery.submit()
if usernamequery['query']['users'][0]['editcount']>1000:
_cache[tuple([username, 'check_user_edits'])]=True
return True
else:
_cache[tuple([username, 'check_user_edits'])]=False
return False
except:
_cache[tuple([username, 'check_user_edits'])]=False
return False
def check_user(fapage):
First_user=''
try:
page_history=fapage.getVersionHistory()
First_user=page_history[-1][2]
if check_user_edits(First_user):
return True,First_user
else:
return False,First_user
except:
return False,First_user
def add_nav(preloadingGen,username_r):
for tem in preloadingGen:
tem_title=tem.title().replace('الگو:','')
if not re.sub(r'[^صثقفغعهخحجچشسیبلاتنمکگظطزرذدپوژآيئؤًٌٍَُِّْٔ]','',tem_title).strip():
continue
if '/' in tem_title or '\\' in tem_title:
continue
try:
tem_text=tem.get()
except:
continue
tem_text=tem_text.replace('{{ ','{{').replace('{{ ','{{').replace('{{الگو:','{{').replace('{{Template:','{{').replace('{{template:','{{')
TempTemplates=templatequery(tem.title())
if not TempTemplates:
continue
if not 'Navbox' in TempTemplates and not 'نوار جانبی' in TempTemplates:
continue
if 'Navbox' in TempTemplates:
tempetype='navbox'
if 'نوار جانبی' in TempTemplates:
tempetype='sidebar'
added_template=tem.title().replace('الگو:','').replace('template:','').replace('Template:','')
if tem.namespace()!=10:
continue
redirects=tem.getReferences(redirectsOnly=True)
redirect_list=[]
for i in redirects:
redirect_list.append(i.title().replace('الگو:','').replace('template:','').replace('Template:',''))
links=tem.linkedPages()
link_t=[]
for i in links:
link_t.append(i.title())
links_ref=tem.getReferences()
link_t2=[]
for i in links_ref:
link_t2.append(i.title())
links=[x for x in link_t if x not in link_t2]
links,delink=link_filtering(tem_text,links)
old_tem_text=tem_text
for nonlink in delink:
tem_text=tem_text.replace('[['+nonlink+']]',nonlink.split('|')[0])
if old_tem_text!=tem_text:
tem.put(tem_text,'ربات:برداشتن پیوندهای نالازم')
added_links=[]
for faTitle in links:
try:
fapage=pywikibot.Page(fasite, faTitle)
text=fapage.get()
except pywikibot.exceptions.IsRedirectPageError:
fapage_redi = fapage.getRedirectTarget()
try:
text=fapage_redi.get()
solve_redirect(tem,fapage,fapage_redi)
fapage=fapage_redi
except:
continue
except:
continue
old_text=text
for i in redirect_list:
text=text.replace('{{'+i+'}}','{{'+added_template+'}}').replace('{{'+i+'|','{{'+added_template+'|')
fatemplates=templatequery(fapage.title())
text=text.replace('{{ ','{{').replace(' }}','}}').replace('{{الگو:','{{').strip()
if not fatemplates:
continue
if '{{'+added_template+'}}' not in text and (not added_template in fatemplates):
addtemplate2='[[الگو:'+added_template+']]'
addtemplate='{{'+added_template+'}}'
addtext_result= addtext (fapage,text,addtemplate,addtemplate2,' ',username_r,tempetype)
if addtext_result:
added_links.append(faTitle)
continue
if old_text!=text:
try:
fapage.put(text,'ربات:اصلاح تغییرمسیر ناوباکس')
except:
pass
continue
my_result={}
if added_links:
my_result['msg']='الگو به «'+'»، «'.join(added_links)+'» افزوده شده!'
else:
my_result['msg']='الگو در همهٔ مقالات موجود است!'
print(json.dumps(my_result, ensure_ascii=False))
def main():
gen = None
username_r='User:Yamaha5'
genFactory = pagegenerators.GeneratorFactory()
for arg in sys.argv:
if arg.startswith('-newtem'):
arg=arg.replace(':','')
if len(arg) == 7:
genfa = pagegenerators.NewpagesPageGenerator(site=fasite, total=100, namespaces=(10))
else:
genfa = pagegenerators.NewpagesPageGenerator(site=fasite, total=int(arg[8:]), namespaces=(10))
gen = genfa
else:
gen = genFactory.handle_arg( arg )
if not gen:
sys.exit()
add_nav(gen,username_r)
if __name__ == "__main__":
main()
else:
faPage = pywikibot.Page(fasite, sys.argv[1])
add_nav([faPage],sys.argv[2])