Last active
December 30, 2015 18:05
-
-
Save toto/3c704bb1fd619dcedb63 to your computer and use it in GitHub Desktop.
Exports all comments with metadata for a FB post to XLSX.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'simple_xlsx' | |
require 'pp' | |
require 'net/http' | |
require 'json' | |
require 'uri' | |
require 'csv' | |
ACCESS_TOKEN = 'TOKEN' # fill this with a current access token from (e.g. from the Graph API console) | |
post_ids = %w{ POST_ID } # post IDs go here | |
def get_url(url) | |
unless url.include?('access_token=') | |
if url.include?('?') | |
url << "&access_token=#{ACCESS_TOKEN}" | |
else | |
url << "?access_token=#{ACCESS_TOKEN}" | |
end | |
end | |
unless url.include?('filter=stream') | |
url << '&filter=stream' | |
end | |
uri = URI(url) | |
result = Net::HTTP.get_response(uri) | |
unless result.kind_of?(Net::HTTPOK) | |
raise "Error from FB. Response: #{result}" | |
data = nil | |
else | |
data = JSON.parse(result.body) | |
end | |
end | |
post_ids.each_with_index do |post_id, index| | |
all_comments = [] | |
url = "https://graph.facebook.com/#{post_id}/comments" | |
while url | |
puts "getting #{url}" | |
response = get_url(url) | |
if data = response['data'] | |
all_comments += data | |
end | |
if response['data'].count > 0 && response['paging'] && response['paging']['next'] | |
url = response['paging']['next'] | |
else | |
url = nil | |
end | |
end | |
filename = "video-#{index+1}-post-#{post_id}" | |
full_filename = "#{filename}.xlsx" | |
SimpleXlsx::Serializer.new(full_filename) do |doc| | |
doc.add_sheet("Sheet 1") do |sheet| | |
sheet.add_row(['Datum', 'Post ID', 'Name', 'User ID', 'Kommentar ID', 'Kommentartext', 'Kommentar-Likes']) | |
for comment in all_comments | |
sheet.add_row([ comment['created_time'], | |
post_id.to_s, | |
comment['from']['name'], | |
comment['from']['id'], | |
comment['id'], | |
comment['message'], | |
comment['like_count'] ]) | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment