Advertisement
Termz

UTF-8

Jun 1st, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.40 KB | None | 0 0
  1. #!/usr/bin/python
  2. # coding: utf-8
  3. from urllib import urlencode
  4. from xml.dom import minidom as xml
  5. import urllib2, json
  6. from cookielib import CookieJar
  7. from datetime import datetime
  8. from threading import Thread
  9. from sys import exit
  10.  
  11. class WikiDataUpdater:
  12.     _CDATA = [{"l":"Albania","n":"Albania","i":"167"},{"l":"Argentina","n":"Argentina","i":"27"},{"l":"Australia","n":"Australia","i":"50"},{"l":"Austria","n":"Austria","i":"33"},{"l":"Belarus","n":"Belarus","i":"83"},{"l":"Belgium","n":"Belgium","i":"32"},{"l":"Bolivia","n":"Bolivia","i":"76"},{"l":"Bosnia-Herzegovina","n":"Bosnia and Herzegovina","i":"69"},{"l":"Brazil","n":"Brazil","i":"9"},{"l":"Bulgaria","n":"Bulgaria","i":"42"},{"l":"Canada","n":"Canada","i":"23"},{"l":"Chile","n":"Chile","i":"64"},{"l":"China","n":"China","i":"14"},{"l":"Colombia","n":"Colombia","i":"78"},{"l":"Croatia","n":"Croatia","i":"63"},{"l":"Cyprus","n":"Cyprus","i":"82"},{"l":"Czech-Republic","n":"Czech Republic","i":"34"},{"l":"Denmark","n":"Denmark","i":"55"},{"l":"Egypt","n":"Egypt","i":"165"},{"l":"Estonia","n":"Estonia","i":"70"},{"l":"Finland","n":"Finland","i":"39"},{"l":"France","n":"France","i":"11"},{"l":"Germany","n":"Germany","i":"12"},{"l":"Greece","n":"Greece","i":"44"},{"l":"Hungary","n":"Hungary","i":"13"},{"l":"India","n":"India","i":"48"},{"l":"Indonesia","n":"Indonesia","i":"49"},{"l":"Iran","n":"Iran","i":"56"},{"l":"Ireland","n":"Ireland","i":"54"},{"l":"Israel","n":"Israel","i":"58"},{"l":"Italy","n":"Italy","i":"10"},{"l":"Japan","n":"Japan","i":"45"},{"l":"Latvia","n":"Latvia","i":"71"},{"l":"Lithuania","n":"Lithuania","i":"72"},{"l":"Malaysia","n":"Malaysia","i":"66"},{"l":"Mexico","n":"Mexico","i":"26"},{"l":"Montenegro","n":"Montenegro","i":"80"},{"l":"Netherlands","n":"Netherlands","i":"31"},{"l":"New-Zealand","n":"New Zealand","i":"84"},{"l":"North-Korea","n":"North Korea","i":"73"},{"l":"Norway","n":"Norway","i":"37"},{"l":"Pakistan","n":"Pakistan","i":"57"},{"l":"Paraguay","n":"Paraguay","i":"75"},{"l":"Peru","n":"Peru","i":"77"},{"l":"Philippines","n":"Philippines","i":"67"},{"l":"Poland","n":"Poland","i":"35"},{"l":"Portugal","n":"Portugal","i":"53"},{"l":"Republic-of-China-Taiwan","n":"Republic of China (Taiwan)","i":"81"},{"l":"Republic-of-Macedonia-FYROM","n":"Republic of Macedonia (FYROM)","i":"79"},{"l":"Republic-of-Moldova","n":"Republic of Moldova","i":"52"},{"l":"Romania","n":"Romania","i":"1"},{"l":"Russia","n":"Russia","i":"41"},{"l":"Saudi-Arabia","n":"Saudi Arabia","i":"164"},{"l":"Serbia","n":"Serbia","i":"65"},{"l":"Singapore","n":"Singapore","i":"68"},{"l":"Slovakia","n":"Slovakia","i":"36"},{"l":"Slovenia","n":"Slovenia","i":"61"},{"l":"South-Africa","n":"South Africa","i":"51"},{"l":"South-Korea","n":"South Korea","i":"47"},{"l":"Spain","n":"Spain","i":"15"},{"l":"Sweden","n":"Sweden","i":"38"},{"l":"Switzerland","n":"Switzerland","i":"30"},{"l":"Thailand","n":"Thailand","i":"59"},{"l":"Turkey","n":"Turkey","i":"43"},{"l":"Ukraine","n":"Ukraine","i":"40"},{"l":"United-Arab-Emirates","n":"United Arab Emirates","i":"166"},{"l":"United-Kingdom","n":"UK","i":"29"},{"l":"Uruguay","n":"Uruguay","i":"74"},{"l":"USA","n":"USA","i":"24"},{"l":"Venezuela","n":"Venezuela","i":"28"}]
  13.  
  14.     def __init__(self):
  15.         w = Wiki()
  16.         w.start()
  17.         self.edit_data = []
  18.         print 'Fetching region, mppa and embargo data'
  19.         self.mapXML = self.fetch_map_xml()
  20.         self.parse_data_from_map_xml()
  21.         print 'Done. Fetching resource bonuses.'
  22.         self.bonus_fetcher()
  23.         print 'Done. Fetching tax data.'
  24.         self.fetch_tax_data()
  25.         print 'Done. Fetching latest events.'
  26.         self.fetch_events()
  27.         print 'Done. Editing pages'
  28.         w.params = self.edit_data
  29.         w.doEdit()
  30.  
  31.     def parse_data_from_map_xml(self):
  32.         country_list_code = "<noinclude>This is part of [[Template:Regions]]. When country name is passed to this template it returns a formatted list of regions owned by the country in question. <br /><br /> '''This page is updated automatically updated by a bot. The bot is administrated by [[Code-Y]]. Please refrain from editing this page by hand and if it's out-dated just write on his User Talk.'''</noinclude><includeonly>{{#switch: {{{1}}}|\n"
  33.         regionstable_code = "<noinclude>This is part of [[Template:RegionsTable]]. When country name is passed to this template it returns a formatted list of regions owned by the country in question. <br /><br /> '''This page is updated automatically updated by a bot. The bot is administrated by [[Code-Y]]. Please refrain from editing this page by hand and if it's out-dated just write on his User Talk.'''</noinclude><includeonly>{{#switch: {{{1}}}|\n"
  34.         region_list_code = "<noinclude>This is part of [[Template:Regions]]. When a region name is passed to this template, it returns the current owner country of that region. <br /><br /> '''This page is updated automatically updated by a bot. The bot is administrated by [[Code-Y]]. Please refrain from editing this page by hand and if it's out-dated just write on his User Talk.'''\n\nNotes:\n*If you want to get data for [[Ha'il]] you must pass <code>Ha&amp;#39;il</code> to the template.\n*If you want to get data for [[Svalbard & Jan Mayen]] or [[Yorkshire & Humberside]], you need to replace '&amp;' with '&amp;amp;'</noinclude><includeonly>{{#switch: {{{1}}}|\n"
  35.         mpp_code="<noinclude>When a country name is passed to this template, it returns the current list of MPP's that country has with expire date. <br /><br /> '''This page is updated automatically updated by a bot. The bot is administrated by [[Code-Y]]. Please refrain from editing this page by hand and if it's out-dated just write on his User Talk.'''</noinclude><includeonly>{{#switch: {{{1|}}}|\n"
  36.         embargo_code = "<noinclude>When a country name is passed to this template, it returns the current list of embargoes that country has with expire date. <br /><br /> '''This page is updated automatically updated by a bot. The bot is administrated by [[Code-Y]]. Please refrain from editing this page by hand and if it's out-dated just write on his User Talk.'''</noinclude><includeonly>{{#switch: {{{1|}}}|\n"
  37.         countries = self.mapXML.getElementsByTagName('country')
  38.         for c in countries:
  39.             capitalcity = ''
  40.             regions = list()
  41.             country_link = c.getAttribute("link")
  42.             country_name = self.cNameFromLink(country_link)
  43.             country_list_code += '  %s =' % country_name
  44.             region_elements = c.getElementsByTagName('region')
  45.             names = []
  46.                
  47.             for reg in region_elements:
  48.                 region_name = reg.getAttribute('name')
  49.                 wikiname = self.wikiregion(region_name)
  50.                 region_list_code += '  %s=%s|\n' % (wikiname.replace('&','&amp;').replace("'",'&#39;'), country_name)
  51.                 capital = reg.getAttribute('capitalcity')
  52.                 if capital == '1':
  53.                     capitalcity = wikiname.replace('&','&amp;').replace("'",'&#39;')
  54.                     wikiname = u' · [[%s]] [[File:Icon-capital.gif|link=Capital (political)]]' % wikiname
  55.                 else:
  56.                     names.append(wikiname.replace('&','&amp;').replace("'",'&#39;'))
  57.                     wikiname = u' · [[%s]]' % wikiname
  58.                 regions.append(wikiname)
  59.             regions.sort()
  60.             names.sort()
  61.             regionstable_code += '  %s = {{RegionsTable/Table|%s|showprod={{{showprod}}}|showmap={{{showmap}}}|capital=%s}}|\n' % (country_name,'|'.join(names),capitalcity)
  62.             country_list_code += ''.join(regions)
  63.             country_list_code += '|\n'
  64.  
  65.             mpp_code += '  %s={{MPPList/List' % country_name
  66.             index = 0
  67.             c_mpps = []
  68.             for mpp in c.getElementsByTagName('mpp'):
  69.                 mppc = self.cNameFromId(mpp.getAttribute('c_id'))
  70.                 expires = mpp.getAttribute('expires')
  71.                 c_mpps.append('|cx=%s|ex=%s' % (mppc, expires))
  72.  
  73.             c_mpps.sort()
  74.            
  75.             for mpp in c_mpps:
  76.                 mpp_code = '%s%s' % (mpp_code, mpp.replace('cx=','c%s=' % str(index)).replace('ex=','e%s=' % str(index)))
  77.                 index += 1
  78.  
  79.             mpp_code = '%s}}|\n' % mpp_code
  80.  
  81.             embargo_code = '%s  %s={{MPPList/List|type=embargo'% (embargo_code, country_name)
  82.             index = 0
  83.  
  84.             c_embargoes = []
  85.             for embargo in c.getElementsByTagName('embargo'):
  86.                 embargoc = self.cNameFromId(embargo.getAttribute('c_id'))
  87.                 expires = embargo.getAttribute('expires')
  88.                 c_embargoes.append('|cx=%s|ex=%s' % (embargoc, expires))
  89.  
  90.             c_embargoes.sort()
  91.  
  92.             for embargo in c_embargoes:
  93.                 embargo_code = '%s%s' % (embargo_code, embargo.replace('cx=','c%s=' % str(index)).replace('ex=','e%s=' % str(index)))
  94.                 index += 1
  95.  
  96.             embargo_code = '%s}}|\n' % embargo_code
  97.  
  98.         mpp_list = '%s  #default=error}}</includeonly>' % mpp_code
  99.         embargo_list = '%s  #default=error}}</includeonly>' % embargo_code
  100.         m_data = {'bot':'','format':'txt','action':'edit','token':'','title':'Template:MPPList/Data','summary':'Cron update.','text':mpp_list}
  101.         e_data = {'bot':'','format':'txt','action':'edit','token':'','title':'Template:EmbargoList/Data','summary':'Cron update.','text':embargo_list}
  102.  
  103.         country_list_code += '#default=FAIL\n}}</includeonly>'
  104.         regionstable_code += '#default=FAIL\n}}</includeonly>'
  105.         region_list_code += '  #default=FAIL\n}}</includeonly>'
  106.         country_list_code = country_list_code.replace(u'= · ','=')
  107.         temp = {'bot':'','format':'txt','action':'edit','token':'','title':'Template:Regions/Regions','summary':'Cron update.','text':country_list_code.encode('UTF-8')}
  108.         temp2 = {'bot':'','format':'txt','action':'edit','token':'','title':'Template:RegionsTable/OwnerData','summary':'Cron update','text':regionstable_code.encode('UTF-8')}
  109.         temp3 = {'bot':'','format':'txt','action':'edit','token':'','title':'Template:Regions/Owners','summary':'Cron update.','text':region_list_code.encode('UTF-8')}
  110.         self.edit_data.append(temp)
  111.         self.edit_data.append(temp2)
  112.         self.edit_data.append(temp3)
  113.         self.edit_data.append(m_data)
  114.         self.edit_data.append(e_data)
  115.  
  116.     def bonus_fetcher(self):
  117.         _DATA_URL = 'http://api.1way.it/erep/regions/'
  118.         _WPN_RES = 'Iron Oil Saltpeter Aluminum Rubber'
  119.         _FOD_RES = 'Grain Fruits Fish Deer Cattle'
  120.         bonusdata = []
  121.         code = "<noinclude>This template can be used to get the amount of resource bonuses provided in different countries.\n\n==Usage==\n*For food and food raw material use: <code><nowiki>{{ResourceBonus|</nowiki>''country_name''_f}}</code>\n*For weapons and weapon raw material use: <code><nowiki>{{ResourceBonus|</nowiki>''country_name''_w}}</code>\n\n=== Example ===\n*<code><nowiki>{{ResourceBonus|Finland_f}}</nowiki></code> --> {{ResourceBonus|Finland_f}} (the percentage of food bonus in Finland)\n\n'''Note''': The output is plain number without '%' sign!\n\n<small>''Data is provided by the [http://api.1way.it/erep/ heapy (Hate Erepublik API)] made by Martin Sileno.''</small></noinclude><includeonly>{{#switch: {{{1|}}}|\n"
  122.  
  123.         for i in self._CDATA:
  124.             url = '%s%s' % (_DATA_URL, i["i"])
  125.             response = urllib2.urlopen(url)
  126.             json_data = json.loads(response.read())
  127.             country = json_data["country"]["name"]
  128.             regions = json_data["regions"]
  129.             weapon_raws = []
  130.             food_raws = []
  131.             for region in regions:
  132.                 route = region["is_connected"]
  133.                 if route:
  134.                     res = region["resource"]["name"]
  135.                     if res in _WPN_RES:
  136.                         weapon_raws.append(res)
  137.  
  138.                     elif res in _FOD_RES:
  139.                         food_raws.append(res)
  140.  
  141.                     else:
  142.                         print 'Unknown resource: %s' % res
  143.  
  144.             food_raws = list(set(food_raws))
  145.             weapon_raws = list(set(weapon_raws))
  146.             food_bonus = len(food_raws) * 20
  147.             weapon_bonus = len(weapon_raws) * 20
  148.             bonusdata.append('  %s_f=%s' % (country, food_bonus))
  149.             bonusdata.append('  %s_w=%s' % (country, weapon_bonus))
  150.  
  151.         code += '|'.join(bonusdata)
  152.         code = '%s|\n  #default=err\n}}</includeonly>' % code
  153.         self.edit_data.append({'bot':'','format':'txt','action':'edit','token':'','title':'Template:ResourceBonus','summary':'Cron update.','text':code})
  154.  
  155.     def fetch_tax_data(self):
  156.         url = 'http://api.1way.it/erep/tax/0'
  157.         try:
  158.             data = urllib2.urlopen(url)
  159.         except:
  160.             print 'Error fetching tax data'
  161.         taxes = json.loads(data.read())
  162.  
  163.         code = '<noinclude>{{Documentation}}</noinclude><includeonly>{{#switch: {{{1|}}}|'
  164.         ind_codes = {"Food":"food","Iron":"wrm","Grain":"frm","Weapons":"weapons","Hospital":"hosp","Defense Systems":"ds","Housing":"house","Moving Tickets":"mt"}
  165.         for c in taxes:
  166.             name = c["country"]["name"]
  167.             timestamp = c["last_updated_ts"]
  168.             tax_data = c["taxes"]
  169.             code += '%s_last=%i|' % (name, timestamp)
  170.  
  171.             for inds in tax_data:
  172.                 try:
  173.                     ind = ind_codes[inds["industry"]["name"]]
  174.                 except NameError:
  175.                     print "Unknown industry: %s" % inds["industry"]["name"]
  176.                     continue
  177.  
  178.                 vat = inds["vat"]
  179.                 imp = inds["import"]
  180.                 inc = inds["income"]
  181.  
  182.                 if ind == 'wrm' or ind == 'frm':
  183.                     code += '%s_%s_income=%i|%s_%s_import=%i|' % (name, ind, inc, name, ind, imp)
  184.                 elif ind == 'food' or ind == 'weapons':
  185.                     code += '%s_%s_income=%i|%s_%s_import=%i|%s_%s_vat=%i|' % (name, ind, inc, name, ind, imp, name, ind, vat)
  186.                 else:
  187.                     code += '%s_%s_import=%i|%s_%s_vat=%i|' % (name, ind, imp, name, ind, vat)
  188.  
  189.         code += '#default=<span title="Error: Nothing matched your query. Either something is not working or there\'s no such tax for the industry.">0</span>}}</includeonly>'
  190.  
  191.         self.edit_data.append({'bot':'','format':'txt','action':'edit','token':'','title':'Template:Taxes/Data','summary':'Cron update.','text':code})
  192.  
  193.     def fetch_events(self):
  194.         url = 'http://www.erepublik.com/rss/allMilitaryEvents'
  195.         try:
  196.             rss = urllib2.urlopen(url)
  197.         except Exception, e:
  198.             print 'Error fetching latest events: %s' % e
  199.  
  200.         events = xml.parseString(rss.read()).getElementsByTagName('entry')
  201.         event_code = ''
  202.  
  203.         for i in range(10):
  204.             event = self.format_event(events[i].getElementsByTagName('title')[0].firstChild.data)
  205.             event_code += '* %s\n' % event
  206.  
  207.         self.edit_data.append({'bot':'','format':'txt','action':'edit','token':'','title':'Portal:Main Page/Latest events','summary':'Cron update.','text':event_code.encode('UTF-8')})
  208.  
  209.     def format_event(self, string):
  210.         if 'was secured' in string:
  211.             alue = self.wikiregion(string.split(' was secured')[0])
  212.             voittaja = string.split('secured by ')[1].split(' in the war')[0]
  213.             if 'Resistance force' in string:
  214.                 haviaja = string.split('force of ')[1]
  215.                 koodi = '[[%s]] was secured by [[%s]] in the war versus [[%s|Resistance force of %s]]' % (alue, voittaja, haviaja, haviaja)
  216.             else:
  217.                 haviaja = string.split('war versus ')[1]
  218.                 koodi = '[[%s]] was secured by [[%s]] in the war versus [[%s]]' % (alue, voittaja, haviaja)
  219.             return koodi
  220.  
  221.         if 'was conquered' in string:
  222.             alue = self.wikiregion(string.split(' was conquered')[0])
  223.             voittaja = string.split('conquered by ')[1].split(' in the war')[0]
  224.             tappio = string.split('war versus ')[1]
  225.             if 'Resistance' in voittaja:
  226.                 voittaja = voittaja.split('force of ')[1]
  227.                 koodi = '[[%s]] was conquered by [[%s|Resistance force of %s]] in the war versus [[%s]]' % (alue, voittaja, voittaja, tappio)
  228.             else:
  229.                 koodi = '[[%s]] was conquered by [[%s]] in the war versus [[%s]]' % (alue, voittaja, tappio)
  230.             return koodi
  231.  
  232.         if 'resistance has started' in string:
  233.             alue = self.wikiregion(string.split('started in ')[1])
  234.             string = 'A [[resistance]] has started in [[%s]], [[{{Regions/Owners|%s}}]]' % (alue, alue.replace('&','&amp;').replace("'","&#39;"))
  235.             return string
  236.  
  237.         if 'attacked' in string:
  238.             att = string.split(' attacked')[0]
  239.             alue = self.wikiregion(string.split('attacked ')[1].split(',')[0])
  240.             defe = string.split(', ')[1]
  241.             string = '[[%s]] attacked [[%s]], [[%s]]' % (att, alue, defe)
  242.             return string
  243.  
  244.         if 'signed an alliance' in string:
  245.             maa1 = string.split(' signed')[0]
  246.             maa2 = string.split(' with ')[1]
  247.             string = '[[%s]] signed an [[alliance]] with [[%s]]' % (maa1, maa2)
  248.             return string
  249.  
  250.         if ' as a Natural Enemy' in string:
  251.             maa1 = string.split(' has declared')[0]
  252.             maa2 = string.split('has declared ')[1].split(' as a Natu')[0]
  253.             string = '[[%s]] has declared [[%s]] as a [[Natural enemy]]' % (maa1, maa2)
  254.             return string
  255.  
  256.         if 'is no longer' in string:
  257.             maa1 = string.split(' is no longer')[0]
  258.             maa2 = string.split('Enemy for ')[1]
  259.             string = '[[%s]] is no longer a [[natural enemy]] for [[%s]]' % (maa1, maa2)
  260.             return string
  261.  
  262.         if 'no longer has a Natural Enemy' in string:
  263.             maa = string.split(' no longer has a')[0]
  264.             string = '[[%s]] no longer has a [[Natural enemy]]' % maa
  265.             return string
  266.  
  267.         if 'was impeached' in string:
  268.             maa = string.split('President of ')[1].split(',')[0]
  269.             nimi = string.split(', was impeached')[0].split(', ')[1]
  270.             string = 'The [[President]] of [[%s]], [[%s]], was [[Impeachment|impeached]]' % (maa, nimi)
  271.             return string
  272.  
  273.         if 'signed a peace treaty' in string:
  274.             maa = string.split(' signed a')[0]
  275.             maai = string.split('treaty with ')[1]
  276.             string = '[[%s]] signed a [[peace treaty]] with [[%s]]' % (maa, maai)
  277.             return string
  278.  
  279.         return string
  280.  
  281.     def fetch_map_xml(self):
  282.         try:
  283.             api_xml = xml.parseString(urllib2.urlopen(self.maplink()).read())
  284.             if len(api_xml.getElementsByTagName('countries')) == 0:
  285.                 exit(1)
  286.             return api_xml
  287.         except IOError:
  288.             exit(1)
  289.  
  290.     def wikiregion(self, r):
  291.         if 'ko District' in r:
  292.             return unicode('Brčko District','UTF-8')
  293.         else:
  294.             return r.replace("Friuli-","Friuli ").replace("Haifa d","Haifa D").replace("Maluku i","Maluku I").replace("Trentino-","Trentino ")
  295.  
  296.     def maplink(self):
  297.         time = datetime.now()
  298.         y = time.year
  299.         m = time.month
  300.         d = time.day
  301.  
  302.         if m < 10:
  303.             m = '0%i' % m
  304.  
  305.         if d < 10:
  306.             d = '0%i' % d
  307.  
  308.         timestring = "%s%s%s" % (y, m, d)
  309.  
  310.         apiurl = 'http://api.erepublik.com/map/data/%s' % timestring
  311.         return apiurl
  312.  
  313.  
  314.     def cNameFromLink(self, link):
  315.         for c in self._CDATA:
  316.             if c["l"] == link:
  317.                 return c["n"]
  318.  
  319.         print "No country found with link %s" % link
  320.  
  321.     def cNameFromId(self, cid):
  322.         for c in self._CDATA:
  323.             if c["i"] == cid:
  324.                 return c["n"]
  325.  
  326.         print "No country found with ID %s" % cid
  327.  
  328. class Wiki(Thread):
  329.     def __init__(self):
  330.         Thread.__init__(self)
  331.  
  332.     def run(self):
  333.         self.wiki_api_url = 'http://wiki.erepublik.com/api.php'
  334.         self.params = None
  335.         self.opener = None
  336.         self.login()
  337.  
  338.     def login(self):
  339.         name = 'SampoBot'
  340.         pw = 'bottaillaan'
  341.         logindata = {'action':'login','format':'xml','lgname':name,'lgpassword':pw}
  342.  
  343.         request = urllib2.urlopen(self.wiki_api_url, urlencode(logindata))
  344.         logindata["lgtoken"] = xml.parseString(request.read()).getElementsByTagName('login')[0].getAttribute('token')
  345.         confirm = urllib2.urlopen(self.wiki_api_url,urlencode(logindata))
  346.         result = xml.parseString(confirm.read()).getElementsByTagName('login')[0].getAttribute('result')
  347.  
  348.         if result == 'Success':
  349.             self.opener = opener
  350.             if self.params is not None:
  351.                 self.doEdit()
  352.  
  353.         else:
  354.             print 'Error: %s' % result
  355.             exit(1)
  356.  
  357.     def doEdit(self, mdata=None):
  358.         if mdata is not None:
  359.             self.params = mdata
  360.  
  361.         if self.opener is None: return
  362.  
  363.         pages = [x["title"] for x in self.params]
  364.         self.fetch_edit_tokens(pages)
  365.         self.do_edit()
  366.  
  367.     def fetch_edit_tokens(self, pages):
  368.         names = "|".join(pages)
  369.         query_paramns = {"action":"query","prop":"info","intoken":"edit","format":"xml","titles":names}
  370.         query = urllib2.urlopen(self.wiki_api_url, urlencode(query_paramns))
  371.         response = query.read()
  372.         response_xml = xml.parseString(response)
  373.         tokens = response_xml.getElementsByTagName('page')
  374.  
  375.         for t in tokens:
  376.             token = t.getAttribute('edittoken')
  377.             page = t.getAttribute('title')
  378.             self.add_token(token, page)
  379.  
  380.     def add_token(self, token, page):
  381.         for item in self.params:
  382.             if item["title"] == page:
  383.                 item["token"] = token
  384.                 break
  385.  
  386.     def do_edit(self):
  387.         for page in self.params:
  388.             edit = urllib2.urlopen(self.wiki_api_url, urlencode(page))
  389.             result = edit.read()
  390.  
  391.             if 'nochange' in result:
  392.                 print '%s: No changes after latest update.' % page["title"]
  393.  
  394.             elif 'Success' in result:
  395.                 print '%s: Success' % page["title"]
  396.  
  397.             else:
  398.                 print '%s: Error - Response was %s' % (page["title"], result)
  399.  
  400.  
  401. if __name__ == '__main__':
  402.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(CookieJar()))
  403.     opener.add_headers = [('User-Agent','WikiBot/Python-urllib/2.7')]
  404.     urllib2.install_opener(opener)
  405.     w = WikiDataUpdater()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement