ig_bot/unsorted/ghost-api-jwt.py

67 lines
2.3 KiB
Python
Raw Normal View History

2024-05-25 09:13:33 +02:00
import requests
import os
import re
import jwt
from datetime import datetime
# Setup
blog_url = "https://sij.ai"
# GHOST_API_URL=https://sij.ai/ghost/api/admin
# GHOST_CONTENT_KEY = "22885b1ec3707899dea77020f9"
# GHOST_API_KEY = '65f918acd453d100019bc003:5e1be9fb237df64f985021663dd8af5718e7524b255229c630c1f6a416a58db3'
OPENAI_API_KEY=os.getenv('OPENAI_API_KEY')
GHOST_API_KEY=os.getenv('GHOST_API_KEY')
GHOST_CONTENT_KEY=os.getenv('GHOST_CONTENT_KEY')
GHOST_API_URL=os.getenv('GHOST_API_URL')
key_id, key_secret = GHOST_API_KEY.split(":")
# Generate the JWT token for Admin API
token = jwt.encode({
"iat": int(datetime.now().timestamp()),
"exp": int(datetime.now().timestamp()) + 5 * 60,
"aud": "/v3/admin/"
},
bytes.fromhex(key_secret),
algorithm="HS256",
headers={"kid": key_id}
)
# Fetch posts using the Content API
fetch_url = f"{GHOST_API_URL}/ghost/api/v3/content/posts/?key={GHOST_CONTENT_KEY}&limit=all&fields=id,html,updated_at"
response = requests.get(fetch_url)
if response.status_code != 200:
print(f"Failed to fetch posts. Status code: {response.status_code}")
exit()
posts = response.json()['posts']
for post in posts:
# Regex to find the figure tag
pattern = r'(<figure class="kg-card kg-image-card">.*?</figure>)'
match = re.search(pattern, post['html'], re.DOTALL)
if match:
figure_html = match.group(0)
# Remove the figure tag and then prepend it to the HTML content
modified_html = re.sub(pattern, '', post['html'], count=1)
new_html = figure_html + modified_html # Prepending figure to the HTML
# Update the post using the Admin API
update_url = f"{GHOST_API_URL}/ghost/api/v3/admin/posts/{post['id']}/"
headers = {"Authorization": f"Ghost {token}"}
data = {
"posts": [{
"html": new_html,
"updated_at": post['updated_at'], # Include the required 'updated_at' field
"tags": [{"name": "aigenerated"}]
}]
}
update_response = requests.put(update_url, json=data, headers=headers)
if update_response.status_code == 200:
print(f"Successfully updated post {post['id']}")
else:
print(f"Failed to update post {post['id']}: {update_response.text}")
else:
print("No figure tag found in this post.")