Topic: Swapping Favs and Upvotes?

Posted under General

A little backstory:

When I first found this site, I didn't know why would you need both the favorite and upvote buttons, so I choose to mark images that I liked by faving them.
Then, as time passed and I found images that I really liked, I had to use the remaining option, upvote, to mark my favorite images.

So, currently I'm using the fav/upvote functionality in the wrong way.

Is there an easy way to swap them or it has to be done using the API?

zamary said:
A little backstory:

When I first found this site, I didn't know why would you need both the favorite and upvote buttons, so I choose to mark images that I liked by faving them.
Then, as time passed and I found images that I really liked, I had to use the remaining option, upvote, to mark my favorite images.

So, currently I'm using the fav/upvote functionality in the wrong way.

Is there an easy way to swap them or it has to be done using the API?

no, maybe ask an admin

If you're looking to view your upvotes like you do your favorites, simply search votedup:zamary

There is a way using the API. Assuming you've both favourited and upvoted the posts you really liked, then this slightly edited script below from forum #29460 by Pup and MatrixMash should work. Just follow the instructions on the linked forum but use this script. The script in the linked forum will upvote and unfavourite all of your favourites but I have edited it so that it excludes posts you have faved and upvoted, leaving them as they are, i.e. posts you have only faved will be swapped with an upvote.

Script
# From https://e621.net/forum_topics/29460

# uncomment for a list of all http requests sent out
#import logging
#logging.basicConfig(level=logging.DEBUG)
import subprocess
import sys, time, os
from pathlib import Path
try:
	import requests
	from requests.auth import HTTPBasicAuth
except ModuleNotFoundError:
	print("error - Could not find module 'requests'.")
	print("If this next part fails, you can probably install it manually with this command:")
	print("python3 -m pip install requests")
	a = input("Try to install it automatically? y/n: ")
	if not a.lower().startswith("y"):
		print("Aborting...")
		exit()


	returnCode = subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
	if returnCode != 0:
		print("Something went wrong installing the module.")
		print("Return code: {}".format(returnCode))
		print("Aborting...")
		exit()
	print("Ok, installed. Proceeding...")
	import requests
	from requests.auth import HTTPBasicAuth


# File paths
scriptDir = Path(__file__).resolve().parent
apikeyPath = scriptDir.joinpath("apikey.txt")

# API URL paths
postsURL="https://e621.net/posts.json"
postVoteURL="https://e621.net/posts/{}/votes.json"
favIDURL="https://e621.net/favorites/{}.json"

# Rate limiting
rateLimit = 1
lastTimeValue = time.time()
def rateLimitThread():
	global lastTimeValue
	elapsedTime = time.time() - lastTimeValue
	if elapsedTime <= rateLimit:
		time.sleep(rateLimit-elapsedTime)
	lastTimeValue = time.time()

def inputLogin():
	print("Please input your username and API key.")
	if sys.platform != "win32": # Bash on linux. idk for macos/darwin
		print("You may be able to paste into this terminal with Ctrl + Shift + v.")
	apiUsername = input("Username: ").rstrip("\n")
	apiKey = input("Key: ").rstrip("\n")
	return apiUsername, apiKey

# Load API key from file
try:
	with open(apikeyPath) as apikeyFile:
		apiTxt = apikeyFile.read().splitlines()
	apiUsername = apiTxt[0].split("=")[1].strip().replace(" ", "_")
	apiKey = apiTxt[1].split("=")[1].strip()
except FileNotFoundError:
	apiUsername, apiKey = inputLogin()
	a = input("Save your login to file for next time? y/n: ")
	if a.lower().startswith("y"):
		with open(apikeyPath, "w") as apikeyFile:
			raw = "username={}\napi_key={}".format(apiUsername, apiKey) # "\n" instead of os.linesep because file.write() convert automagically in text mode
			apikeyFile.write(raw)
	print("Ok. Proceeding...")

session = requests.Session()
session.auth = HTTPBasicAuth(apiUsername, apiKey)

# User-Agent header
# Add "edited by <username>" if you edit this script
session.headers = {"User-Agent":"Faves_to_upvotes_mm/1.0 (by Pup on E621 edited by MatrixMash edited by Portaloo)"}

# Params
favParams = {"limit":320, "tags":"fav:{} -votedup:{}".format(apiUsername,apiUsername)}
voteParams = {"score":1, "no_unvote":"true"}

retry_limit = 5
retry_break = 3

postCount = 0
lowestID = -1
stop = False
try:
	while not stop:
		# Get 320 favourited posts
		rateLimitThread()
		response = session.get(postsURL, params=favParams)
		if response.status_code != 200:
			print('Exception: API returned non-200 status code while fetching favorites list: ' + str(response.status_code))
			print(response.json())
			print('Trying again.')
			for _ in range(retry_limit):
				print('wating {} seconds...'.format(retry_break))
				time.sleep(retry_break)
				response = session.get(postsURL, params=favParams)
				if response.status_code == 200:
					break
			else:
				print('Error: tried {} times and still failed.'.format(retry_limit))
				print('Aborting...')
				response.raise_for_status()
		
		returnedJSON = response.json()
		
		if len(returnedJSON["posts"]) < 320:
			stop = True

		for post in returnedJSON["posts"]:
		
			if post["id"] < lowestID or lowestID == -1:
				lowestID = post["id"]
				favParams["page"] = "b" + str(lowestID)
			try:
				print("Updating post #" + str(post["id"]))
				
				# Upvote the post
				rateLimitThread()
				response = session.post(postVoteURL.format(str(post["id"])), params=voteParams)
				response.raise_for_status()
				
				# Un-favourite the post
				rateLimitThread()
				response = session.delete(favIDURL.format(str(post["id"])))
				response.raise_for_status()
				
				postCount += 1
			except requests.exceptions.HTTPError:
				print('Exception: api returned non-200 status code ' + str(response.status_code))
				print(response.json())
				print('Skipping that post for now.')
except KeyboardInterrupt:
	print("Updated {} posts.".format(postCount))
else:
	print("All posts checked.")

  • 1