Created
May 2, 2020 13:17
-
-
Save jthingelstad/70ddb03da863f53c5ec622297c123db1 to your computer and use it in GitHub Desktop.
Script to import a JSONFeed file and referenced images to micro.blog.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# -*- coding: utf-8 -*- | |
import json | |
import pypandoc | |
import re | |
import requests | |
import os.path | |
import sys | |
import time | |
headers = { | |
'Authorization': 'Bearer XXXXXX', | |
} | |
count = 0 | |
with open('feed2.json') as f: | |
data = json.load(f) | |
for i in data['items']: | |
count = count + 1 | |
print ("%s" % count) | |
print (i['title']) | |
print (i['date_published']) | |
md = pypandoc.convert_text(i['content_html'], 'md', format='html') | |
# print ("Before uploading images...") | |
# print (md) | |
urls = re.findall(r'(?:https://www.thingelstad.com)?(/assets/[\.\w\d\/\_\-]+)', md) | |
for u in urls: | |
# Make sure the file exists to upload | |
filepath = '.../thingles.github.io%s' % u | |
if not os.path.isfile(filepath): | |
print ("Cannot find %s" % filepath) | |
sys.exit(1) | |
else: | |
fsize = os.path.getsize(filepath) | |
print ("Found %s (%s)..." % (filepath, fsize)) | |
# Upload the image to micro.blog | |
files = { | |
'file': (filepath, open(filepath, 'rb')), | |
} | |
response = requests.post('https://micro.blog/micropub/media', headers=headers, files=files) | |
print (response) | |
# get location header | |
new_image = response.headers['location'] | |
print ("%s -> %s" % (u, new_image)) | |
# input("Press Enter to continue...") | |
# Update the markdown to use the new URL | |
md = re.sub(rf'(?:https://www.thingelstad.com)?{u}', new_image, md) | |
time.sleep(2) | |
# print ("After uploading images...") | |
# print (md) | |
print ("Sending to micro.blog...") | |
data = { | |
'name': i['title'], | |
'content': md, | |
'published': i['date_published'] | |
} | |
print (data) | |
response = requests.post('https://micro.blog/micropub', headers=headers, data=data) | |
print (response.text) | |
time.sleep(2) | |
# input("Press Enter to continue...") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment