-
-
Save hyuki/eac080de50ced8f9ac96a366b6890f43 to your computer and use it in GitHub Desktop.
瞬間日記のバックアップをesaにまとめてアップロードするRubyスクリプト
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
require 'pp' | |
require 'esa' | |
def parse | |
@info_list = [] | |
@data.each do |line| | |
@info = {} | |
if line.match(/^(2.*)$/) | |
date = $1 # "2023年8月14日 月曜日\n" | |
if date.match(/^(\d+)年(\d+)月(\d+)日 /) | |
@info[:year] = $1 | |
@info[:month] = sprintf("%02d", $2.to_i) | |
@info[:day] = sprintf("%02d", $3.to_i) | |
else | |
abort "Date format" | |
end | |
@info[:title] = date | |
line.split(/\n/).each do |s| | |
if s.match(/^([^-\s#\d\n][^。]{,50})/) | |
@info[:title] = $1 | |
break | |
end | |
end | |
if @info[:title].match(%r{/}) | |
@info[:title] = date | |
end | |
@info[:text] = line | |
pp @info | |
@info_list << @info | |
end | |
end | |
end | |
def init | |
@data = DATA.to_a.join('').split(/^\* /) | |
# https://github.com/esaio/esa-ruby | |
# https://docs.esa.io/posts/102 | |
@client = Esa::Client.new( | |
access_token: ENV['MESA_ESA_ACCESS_TOKEN'], # 環境変数からアクセストークンを得る | |
current_team: ENV['MESA_ESA_TEAM']) # 環境変数からチーム名を得る | |
end | |
def post | |
skips = 0 # 中断して途中から再開するときに | |
data = @info_list | |
data.each_with_index do |info, index| | |
next if index < skips | |
params = { | |
name: info[:title] + " #momentdiary", | |
category: "瞬間日記/#{info[:year]}/#{info[:month]}/#{info[:day]}", | |
body_md: info[:text], | |
wip: false, | |
} | |
response = @client.create_post(params) | |
case response.status | |
when 201 | |
puts "index = #{index} of #{data.size}: created: #{response.body["full_name"]}" | |
when 429 | |
retry_after = (response.headers['Retry-After'] || 20 * 60).to_i | |
puts "rate limit exceeded: will retry after #{retry_after} seconds." | |
else | |
puts "failure with status: #{response.status}" | |
end | |
puts "X-Ratelimit-Remaining: #{response.headers['X-Ratelimit-Remaining']}" | |
if response.headers['X-Ratelimit-Remaining'].to_i < 10 | |
puts "残り少ないのでいったん終了" | |
exit | |
end | |
puts "Sleeping..." | |
sleep 15 | |
end | |
end | |
init | |
parse | |
post | |
# END以下に瞬間日記のメールバックアップを貼り付ける | |
__END__ | |
* 2023年8月13日 日曜日 | |
- 00:00 | |
日曜日にやったこと1 | |
- 01:00 | |
日曜日にやったこと2 | |
* 2023年8月14日 月曜日 | |
- 02:00 | |
月曜日にやったこと1 | |
- 03:00 | |
月曜日にやったこと2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment