Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import csv
- '''
- this script looks for a csv file "books.csv" formatted as so:
- author,title
- "Andy Weir","Artemis"
- ..
- then, it creates another csv file "books_out.csv" with the added hardcover.app ids for each entry:
- author,title,id
- Andy Weir,Artemis,99422
- ..
- then, it adds these books to the Want To Read list of whoever is the owner of the Bearer authorization
- enjoy!
- i take no responsibility this works for you and doesn't wreck your account or system, run at your own risk and/or peril <3
- ALSO, CHANGE THE auth VARIABLE TO YOUR OWN API KEY!!!
- '''
- auth = "Bearer ..."
- def get_book_id(title, author):
- query = """
- query bookSearch($title: String!, $author: String!) {
- books(
- order_by: {users_read_count: desc}
- where: {_and: [{title: {_ilike: $title}}, {contributions: {author: {name: {_ilike: $author}}}}]}
- ) {
- users_read_count
- title
- image {
- url
- }
- id
- contributions {
- author {
- name
- }
- }
- }
- }"""
- variables = {
- "title": f"%{title}%",
- "author": f"%{author}%"
- }
- headers = {
- "Content-Type": "application/json",
- "Authorization": auth
- }
- response = requests.post(
- 'https://api.hardcover.app/v1/graphql',
- json={
- "query": query,
- "variables": variables
- },
- headers=headers
- )
- try:
- book_found = response.json().get("data").get("books")[0]
- return book_found.get("id") if book_found else -1
- except:
- return -1
- with open("books.csv", mode='r', newline='', encoding='utf-8-sig') as infile:
- reader = csv.DictReader(infile)
- fieldnames = reader.fieldnames + ['id']
- with open("books_out.csv", mode='w', newline='', encoding='utf-8-sig') as outfile:
- writer = csv.DictWriter(outfile, fieldnames=fieldnames)
- writer.writeheader()
- for row in reader:
- print(f"{row['title']} - {row['author']} ...", end="")
- book_id = get_book_id(row['title'], row['author'])
- if book_id != -1:
- print(book_id)
- row['id'] = book_id
- writer.writerow(row)
- else:
- print("NO ID FOUND")
- def wantToRead(id: int):
- query = """
- mutation wantToRead($id: Int!) {
- insert_user_book(object: {
- book_id: $id,
- status_id: 1
- }) {
- id
- }
- }
- """
- variables = {
- "id": id
- }
- headers = {
- "Content-Type": "application/json",
- "Authorization": auth
- }
- response = requests.post(
- 'https://api.hardcover.app/v1/graphql',
- json={
- "query": query,
- "variables": variables
- },
- headers=headers
- )
- print(response.json())
- with open("books_out.csv", mode='r', newline='', encoding='utf-8-sig') as infile:
- reader = csv.DictReader(infile)
- for row in reader:
- id = int(row["id"])
- print(f"Adding {id} - {row['title']} by {row['author']}..")
- wantToRead(id)
Advertisement
Add Comment
Please, Sign In to add comment