Skip to content

Instantly share code, notes, and snippets.

@keith
Last active September 1, 2017 16:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keith/60d9ad84767491a66758 to your computer and use it in GitHub Desktop.
Save keith/60d9ad84767491a66758 to your computer and use it in GitHub Desktop.
Create a medium post from a GitHub flavored markdown file
#!/usr/bin/env ruby
#
# Usage: medium-draft TOKEN FILENAME
# Where TOKEN is a medium integration token and FILENAME is the path to the
# markdown file you'd like to post
#
# Get your token from https://medium.com/me/settings (integration tokens section)
#
# This requires httparty and redcarpet
# Install with:
# [sudo] gem install httparty redcarpet
#
require "httparty"
require "redcarpet"
raise "Usage: medium-draft TOKEN MARKDOWN_FILENAME" unless ARGV.count == 2
token = ARGV.first
filename = ARGV.last
def get_headers(token)
return {
"Content-Type" => "application/json",
"Accept" => "application/json",
"Authorization" => "Bearer #{ token }",
}
end
def get_user_id(token)
response = HTTParty.get("https://api.medium.com/v1/me", {
headers: get_headers(token)
})
if response.code == 200
return response.parsed_response["data"]["id"]
else
abort "Failed to get user ID: #{ response.code } #{ response.parsed_response }"
end
end
def create_draft(user_id, token, filename)
url = "https://api.medium.com/v1/users/#{ user_id }/posts"
renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML,
fenced_code_blocks: true)
html = renderer.render(File.read(filename))
args = {
headers: get_headers(token),
body: {
title: filename,
contentFormat: "html",
content: html,
publishStatus: "draft",
}.to_json,
}
response = HTTParty.post(url, args)
if response.code.between?(200, 299)
puts "Success"
else
abort "Failure: #{ response.code } #{ response.parsed_response }"
end
end
user_id = get_user_id(token)
create_draft(user_id, token, filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment