Skip to content

Instantly share code, notes, and snippets.

@pkutaj
Created October 11, 2024 04:11
Show Gist options
  • Save pkutaj/b291609043c4f9df9f55d3ce489cf8cf to your computer and use it in GitHub Desktop.
Save pkutaj/b291609043c4f9df9f55d3ce489cf8cf to your computer and use it in GitHub Desktop.
Python Script to Publish to dev.to
import webbrowser
import requests
import json
import os
import sys
headers_dev = {
"Content-Type": "application/json",
"api-key": os.environ["DEV_API_KEY"],
}
def main(markdown_path: str, title: str):
markdown_content = get_markdown_content(markdown_path)
if title == "":
input_title = input("Enter the title of the article: ")
publish_article_dev(markdown_content, title)
def get_markdown_content(markdown_path: str):
with open(markdown_path, "r") as file:
markdown_content = file.read()
return markdown_content
def publish_article_dev(markdown_content: str, title: str):
article_payload = {
"article": {
"title": title,
"body_markdown": markdown_content,
"published": False,
}
}
try:
res = requests.post(
url="https://dev.to/api/articles",
headers=headers_dev,
data=json.dumps(article_payload),
)
res.raise_for_status()
print("Article published successfully!")
print("Response:", res.json())
webbrowser.open("https://dev.to/dashboard")
except:
print(f"Failed to publish article. Status code: {res.status_code}")
print("Response:", res.json())
if __name__ == "__main__":
main(markdown_path=sys.argv[1], title=sys.argv[2])
@pkutaj
Copy link
Author

pkutaj commented Oct 11, 2024

Add the following to your .bash_profile

  1. set DEV_API_KEY an an environment variable.
  2. fix fullpath to python script
  3. run publish <fullpath.md> from CLI and done. The title is taken from the filename, to name once and properly. Ensure the path to publish.py below is fixed!
# EXPORT API KEY 
export DEV_API_KEY="<secret>"
# DEV.TO PUBLISHER

function publish {
  set -x
  markdown_path="$1"
  title=$(extract_title "$markdown_path")
  echo "$markdown_path"
  echo "$title"
 # FIX PATH BELOW!
jjkj  python3 /Users/publish.py "$markdown_path" "$title"
  set +x
}

function extract_title {
    filename=$(basename "$1")
    filename="${filename%.*}"
    filename="${filename#*-*-*-}"
    title="${filename//-/ }"
    echo "$title"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment