Page MenuHomePhabricator
Paste P3232

scripts/thanks.py
ActivePublic

Authored by darthbhyrava on Jun 12 2016, 3:39 PM.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
A script which takes a revision ID on the wiki and thanks it on behalf of the user logged in.
Syntax:
python pwb.py thanks [rev]
Params
-rev: - The value of the revisionID to be thanked.
(Start with hardcoded revision 217210 on test:test)
I can call the Thanks API for this, which must be called by `action=thank`. It needs the params `rev`, `source` (optional),
and token=csrf, I must get the csrf token via the Tokens API. And I must have site and user credentials working.
"""
from __future__ import absolute_import, unicode_literals
import pywikibot
import requests
# import urllib
# import urllib2
def thank_rev(rev_id):
"""
Thank the given revision ID on the wiki on behalf of the user logged in.
"""
#Login into the wiki
site = pywikibot.Site()
site.login()
#Get csrf token from site.
token = site.tokens['csrf']
#token = token[:-2]+"%2B%5C"
print rev_id
print token
#GET request (doesn't work, tokens need to be in the POST body):
#response = urllib2.urlopen("https://test.wikipedia.org/w/api.php?action=thank&format=json&rev={0}&token={1}&source=diff".format(rev_id, token))
#html = response.read()
#print html
#Make a POST request to thank the rev_id. (doesn't work, leading to bad token errors)
# url = 'https://test.wikipedia.org/w/api.php?action=thank&format=json'
# values = {'rev' : rev_id,
# 'source' : 'test_thank',
# 'token' : token }
# data = urllib.urlencode(values)
# req = urllib2.Request(url, data)
# response = urllib2.urlopen(req)
# html = response.read()
# print html
#Using requests to make GET or POST requests instead of urlib2
#r = requests.get("https://test.wikipedia.org/w/api.php?action=thank&format=json&rev={0}&token={1}&source=diff".format(rev_id, token))
values = {'rev' : rev_id,
'source' : 'test_thank',
'token' : token }
r = requests.post("https://test.wikipedia.org/w/api.php?action=thank&format=json", data=values)
print (r.text)
def main(*args):
"""
Proces command line arguments and thank the rev
"""
# Process the args
local_args = pywikibot.handle_args(args)
for arg in local_args:
option, sep, value = arg.partition(':')
if option == '-rev':
rev_id = int(value)
#Call the thank method
thank_rev(rev_id)
if __name__ == "__main__":
main()