[Ruby] post to Qiita patching version

1 minute read

Update the article already given to qiita version

There is a record of the version to be posted first to. Furthermore, it is a version that updates the articles already listed in qiita. Below code

ruby post_final.rb post_final.org

You can do something. In the first post, create a new one, and then write the item id to org. If there is, it will patch to that id.

In addition, you can choose’open’ or’teams’. default is’private’.

ruby post_final.rb post_final.org teams

What?

key is

code

require "net/https"
require "json"

def get_title_tags(src)
  $conts = File.read(src)
  title = $conts.match(/\#\+(TITLE|title|Title): (.+)/)[2] || "test"
  m = []
  tags = if m = $conts.match(/\#\+(TAG|tag|Tag|Tag|tags|TAGS|Tags): (.+)/)
m[2].split(',').inject([]) do |l, c|
      l << {name: c.strip} #, versions: []}
    end
else
[{ name: "hoge"}] #, versions: [] }]
end
  p tags
  return title,tags
end

src = ARGV[0] ||'README.org'
title, tags = get_title_tags(src)
p title
p tags

system "emacs #{src} --batch -l ~/.emacs.d/site_lisp/ox-qmd -f org-qmd-export-to-markdown --kill"

lines = File.readlines(src.gsub('org','md'))

m = []
patch = false
if m = $conts.match(/\#\+qiita_id: (.+)/)
  qiita_id = m[1]
  patch = true
else
  qiita_id =''
end


case ARGV[1]
when'teams'
  qiita ='https://nishitani.qiita.com/'
  p access_token = ENV['QIITA_TEAM_WRITE_TOKEN']
  private = false
when'open'
  qiita ='https://qiita.com/'
  p access_token = ENV['QIITA_WRITE_TOKEN']
  private = false
else
  qiita ='https://qiita.com/'
  p access_token = ENV['QIITA_WRITE_TOKEN']
  private = true
end

params = {
  "body": lines.join, #"#test",
  "private": private,
  "title": title,
  "tags": tags
}

if patch
  path = "api/v2/items/#{qiita_id}"
else
  path ='api/v2/items'
end
p qiita+path
uri = URI.parse(qiita+path)

http_req = Net::HTTP.new(uri.host, uri.port)
http_req.use_ssl = uri.scheme === "https"

headers = {"Authorization" => "Bearer #{access_token}",
  "Content-Type" => "application/json"}
if patch
  res = http_req.patch(uri.path, params.to_json, headers)
else
  res = http_req.post(uri.path, params.to_json, headers)
end

p res.message

res_body = JSON.parse(res.body)
res_body.each do |key, cont|
  if key =='rendered_body' or key =='body'
    puts "%20s brabrabra..." %key
    next
  end
  print "%20s %s\n" %[key, cont]
end
system "open #{res_body["url"]}"
qiita_id =res_body["id"]
unless patch
  File.write(src,"#+qiita_id: #{qiita_id}\n"+$conts)
end

Well, refactoring.

Task

When you want to put it in two places, open and teams, you don’t know which one. I wonder if it can be updated automatically around that. . .