Fandom

Zammy Wiki

TyBot/unusedfiles.py

< TyBot

2,249pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

 import getpass
 
##########################################################################
# PyTyBot - A MediaWiki wrapper for use on wikis. 
#    Copyright (C) 2012  TyA <tya.wiki@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##########################################################################
 
import urllib
import urllib2
import cookielib
import json
 
class tybot(object):
 
	def __init__(self,username,password,wiki):
		self.username = username
		self.password = password
		self.wiki = wiki
 
		self.cookiejar = cookielib.CookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
		self.opener.add_headers = [('User-Agent','TyBot')]
		self.login(username, password)
 
	def postToWiki(self,data):
		"""
		POSTs content to the wiki's API in json format
 
		:param data (dict): An dict of what is being posted.
		:returns: the response from the API
		"""
		data = urllib.urlencode(data)
		response = self.opener.open(self.wiki + "/api.php", data);
 
		response = response.read()
		response = json.loads(response, 'utf-8')
 
		return response
 
	def login(self,username,password):
		"""
		Logins into the wiki via API
 
		:param username (str): The username of the user
		:param password (str): The user's password
		:returns: boolean based on success
		"""
		data = {
			"action":"login",
			"lgname":username,
			"lgpassword":password,
			"format":"json"
		}
		response = self.postToWiki(data)
 
		logintoken = response["login"]["token"]
 
		data = {
			"action":"login",
			"lgname":username,
			"lgpassword":password,
			"lgtoken":logintoken,
			"format":"json"
		}
 
		response = self.postToWiki(data)
 
		if response["login"]["result"] == "Success":
			print "Successfully logged in."
			return True
		else:
			print "Failed to login: " + response["login"]["result"]
			return False
 
	def getToken(self):
		"""
		Gets the tokens required to perform many actions
 
		:param none: (uses the username provided when making tybot object)
		:returns: dict of tokens
		"""
		data = {
			"action":"query",
			"prop":"info",
			"intoken":"delete",
			"titles":"Main Page",
			"format":"json"
		}
 
		response = self.postToWiki(data)
		response = response["query"]["pages"].values()
 
		for intoken in response:
			token = intoken["deletetoken"]
		return token
 
	def delete(self,page, token, summary=''):
		""" 
		Deletes pages via the API
 
		:param page (str): The page to delete
		:param summary (str): The deletion summary (Default:'')
		:returns: boolean based on success
		"""
		data = {
			"action":"delete",
			"token":token,
			"title":page,
			"summary":summary,
			"format":"json"
		}
 
		response = self.postToWiki(data)
 
		try:
			print response["error"]["info"]
			return False
		except:
			print "... Success!"
			return True
 
	def query_page(self,type, limit="max", qpoffset=''):
		dataToPost = {
			"action":"query",
			"list":"querypage",
			"qppage":type,
			"qplimit":limit,
			"qpoffset":qpoffset,
			"format":"json"
		}
 
		response = self.postToWiki(dataToPost)
 
		try:
			print response["error"]["code"]
			return False
		except:
			return response
 
############################################################
# End of PyTyBot                                           #
############################################################
 
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
wiki = raw_input("Wiki name (i.e. runescape/community): ")
 
mw = tybot(username, password, "http://" + wiki + ".wikia.com")
token = mw.getToken()
offset = 0
images = []
while True:
	query = mw.query_page("Unusedimages", "max", qpoffset = offset)
 
	for image in query["query"]["querypage"]["results"]:
		images.append(image["title"])
 
	try:
		offset = query["query-continue"]["querypage"]["qpoffset"]
	except KeyError:
		break
 
for image in images:
	print image
	mw.delete(image.encode('utf8'), token, "Automated deletion of unused files.")
	print "... deleted!"

Also on Fandom

Random Wiki