User:Aleksandra96/RationalWiki.py

From RationalWiki
Jump to: navigation, search
import requests
import json
import urllib

class RationalWiki:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.api = 'http://rationalwiki.org/w/api.php'
        self.index = 'http://rationalwiki.org/w/index.php?title='
        self.session = ''
        self.cookies = {}

    def login(self):
        payload = {'format': 'json', 'action': 'login', 'lgname': self.username, 'lgpassword': self.password}
        r = requests.post(self.api, data=payload)
        d = json.loads(r.text)
        login_token = d['login']['token']
        self.cookies = r.cookies
        payload = {'format': 'json', 'action': 'login', 'lgname': self.username, 'lgpassword': self.password, 'lgtoken': login_token}
        r = requests.post(self.api, data=payload, cookies=self.cookies)
        d = json.loads(r.text)
        self.cookies.update(r.cookies)
        print 'Login:', d['login']['result']

    def edit(self, page, text):
        payload = {'format': 'json', 'action': 'query', 'prop': 'info', 'intoken': 'edit', 'rvprop': 'timestamp', 'titles': page}
        r = requests.post(self.api, data=payload, cookies=self.cookies)
        d = json.loads(r.text)
        idn = d['query']['pages'].keys()[0]
        edit_token = d['query']['pages'][idn]['edittoken']
        timestamp = d['query']['pages'][idn]['starttimestamp']
        payload = {'format': 'json', 'action': 'edit', 'title': page, 'summary': 'Bot edit', 'text': text, 'token': edit_token, 'basetimestamp': timestamp}
        r = requests.post(self.api, data=payload, cookies=self.cookies)
        print 'Edit:', json.loads(r.text)['edit']['result']

    def get_wikitext(self, page):
        r = requests.post(self.index + page + '&action=raw', cookies=self.cookies)
        return r.text.encode('utf-8')

    def append(self, page, text, brk=2):
        space = ''
        counter = 0
        while (counter < brk):
            space = space + '\n'
            counter += 1
        wikitext = self.get_wikitext(page).encode('utf-8') + space + text
        self.edit(page, wikitext)

    def get_rc(self, logs):
        i = 0
        titles = []
        users = []
        revid = []
        old_revid = []
        payload = {'format': 'json', 'action': 'query', 'list': 'recentchanges', 'rcprop': 'title|ids|flags|user', 'limit': str(logs)}
        r = requests.post(self.api, data=payload, cookies=self.cookies)
        d = json.loads(r.text)
        while (i <= logs):
            titles.append(d['query']['recentchanges'][i]['title'])
            users.append(d['query']['recentchanges'][i]['user'])
            revid.append(d['query']['recentchanges'][i]['revid'])
            old_revid.append(d['query']['recentchanges'][i]['old_revid'])
            print 'Title:', titles[i], '      User:', users[i]
            i += 1