Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created July 25, 2014 23:20
Show Gist options
  • Save emad-elsaid/554300ca475fab8c991f to your computer and use it in GitHub Desktop.
Save emad-elsaid/554300ca475fab8c991f to your computer and use it in GitHub Desktop.
import links content to facebook comments by mentioning this bot, you'll need to run it periodically using cronjob
#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# **Usage** :
#
# * `ruby readability.rb <accesstoken>`
# this will get a long term access token from the short term one
# you can create a facebook app and get access token from here
# * `ruby readability.rb`
# will start the script
require 'open-uri'
require 'readability' # gem install ruby-readability
require 'koala' # gem install koala
# https://developers.facebook.com/tools/explorer
# scopes required :
# user_groups, publish_stream, manage_notifications, publish_actions
APP_ID = '*******************'
APP_SECRET = '*******************'
NOTIFICATIONS_LIMIT = 100
# this part get the long term access token instead of the
# short term one yo provide and writes it to a file called
# "token" to use it over and over again when you execute
# this script.
if ARGV.size > 0
oauth = Koala::Facebook::OAuth.new(APP_ID, APP_SECRET)
new_access_info = oauth.exchange_access_token_info ARGV.first
File.write 'token', new_access_info['access_token']
puts 'New Access Token written'
exit
end
# respond to comment with mention
def respond_to(graph, post_id)
comment_limit = 8000
post = graph.get_object(post_id)
link = post['link']
return if link.empty?
source = open(link).read
output = Readability::Document.new(source, tags: []).content
output = output.gsub /(\n\s*)+/, "\n"
output = output[0...comment_limit]
return if output.empty?
# posting reply comment
graph.put_object post_id, 'comments', {message: output}
end
begin
oauth_access_token = File.read('token')
$graph = Koala::Facebook::API.new(oauth_access_token)
# get your name
$name = $graph.get_object('me')['name']
# get notifications
notifications = []
page = $graph.get_connections('me','notifications')
begin
notifications += page
end while page = page.next_page and notifications.length<=NOTIFICATIONS_LIMIT
#
# Now lets head to parse and respond to them
#
puts "Notifications found : #{notifications.size}"
notifications.reverse_each do |n|
begin
if n['application'] and n['application']['name'] == 'Groups' and n['title'].include? 'mentioned you'
ids = n['link'].scan /([0-9]+)\/([0-9]+)/
comment = ids.last.last
if ids.size == 1
respond_to $graph, ids.last.last
end
end
rescue
# ignore it
end
# mark notification as read
$graph.put_object(n['id'],'', {unread: false})
end
# please rescue if something went wrong
# thanks,
rescue Exception => e
puts "Error : #{e}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment