drone.ioと連携してFacebookに投稿できるようにした

2013-09-23  /  CI/CD自動化

Twitter版の続きというか、実装は既に出来てたんだけど、Tokenの取得にちょっと手間取ったりして上手く動作しなかったので。

最新記事の取得

これは前回と変わらず。git diff-tree を使って、Jekyll::Postのインスタンスを取得するようにしている。

Facebookに投稿する

最初はfb_graph というgemを使ってたけど、結局curlコマンドを使うようにした。Tokenはdrone.ioと連携の都合があるので、環境変数から取得するようにした。

{% highlight ruby %}
access_token = ENV[‘FACEBOOK_APP_ACCESS_TOKEN’]
user_id = ENV[‘FACEBOOK_USER_ID’]
cmd = “curl -X POST -F ‘message=書きました’ -F ‘access_token=#{access_token}’ -F ’link=http://google.co.jp’ https://graph.facebook.com/#{user_id}/feed"
{% endhighlight %}

無言のシェアでも良いんだけど、一言メッセージを付けるようにしてみた。Twitterに合わせたのかな。

rake タスクにしておく

Twitterの分と合わせて以下のようになった。

{% highlight ruby %}
require ’twitter’
require ‘fb_graph’

def get_site
options = Jekyll.configuration({:safe => true})
site = Jekyll::Site.new(options)
end

def get_post(file)
site = get_site
post = Jekyll::Post.new(site, site.source, “”, File.basename(file))
end

def shared_target_post
git_am_files = git -c core.quotepath=false diff-tree --no-commit-id --name-only --diff-filter=AM -r HEAD _posts.split(/\n/)

git_am_files.each do |file|
post = get_post(file)
if post.published?
return post
end
end

nil
end

namespace :share do

desc ‘Check shared post’
task :check do
post = shared_target_post
if post.nil?
puts “no files updated”
next
end

puts post.name

end

desc ‘Share new post to Twitter’
task :twitter do

post = shared_target_post
if post.nil?
  puts "no files updated"
  next
end

title = post.title
url = "http://kawaken.github.io#{post.url}"

message = %Q(書きました "#{title}" #{url})
Twitter.update message

end

desc ‘Share new post to Facebook’
task :facebook do
post = shared_target_post
if post.nil?
puts “no files updated”
next
end

title = post.title
url = "http://kawaken.github.io#{post.url}"

access_token = ENV['FACEBOOK_APP_ACCESS_TOKEN']
user_id = ENV['FACEBOOK_USER_ID']
cmd = "curl -X POST -F 'message=書きました' -F 'access_token=#{access_token}' -F 'link=#{url}' https://graph.facebook.com/#{user_id}/feed"
system cmd

end
end

desc ‘Share new post’
task :share => [“share:twitter”, “share:facebook”]
{% endhighlight %}

rake share:facebook

で、Facebookに投稿する。ついでに、

rake share

で、TwitterとFacebookの両方に投稿するようにした。

github pages と drone.io の連携

これも前回のまま。

drone.io の設定

Twitterと同様にFacebookも環境変数にtokenを設定しておく。

FACEBOOK_APP_ACCESS_TOKEN
FACEBOOK_USER_ID

ビルドスクリプトは、rake share を呼び出すようにする。

{% highlight sh %}
bundle install –binstubs
bin/jekyll build –safe –trace
rake share
{% endhighlight %}

上手くいけば、TwitterとFacebookの両方に投稿されるはず。

その他

FacebookのToken取得

AccessTokenに色々とあるらしい。UserAccessTokenは有効期限が最大60日で、更新の必要がある。今回のような勝手にポストするような場合にはちょっと使えないかなと思った。60日おきに自分で更新するのはちょっと面倒なので。

代わりにAppAccessTokenを使用した。これは、無期限らしい。利用するユーザに対して、Appの認証が済んでしまえばずっと使えるっぽい。