Skip to content

Instantly share code, notes, and snippets.

@XULRunner42
Created January 16, 2013 20:47
Show Gist options
  • Save XULRunner42/4550806 to your computer and use it in GitHub Desktop.
Save XULRunner42/4550806 to your computer and use it in GitHub Desktop.
This capybara scraper checks my bitcoin address at blockexplorer for an updated balance periodically and posts it to Beeminder.
#!/usr/bin/env ruby
require "capybara"
require "capybara/dsl"
require "capybara-webkit"
require "beeminder"
require 'dbi'
Capybara.run_server = false
Capybara.current_driver = :webkit
Capybara.app_host = "http://blockexplorer.com"
module EAR
class Client
class BlockExplorer
class Tester
include Capybara::DSL
def latest_transaction
first=nil
last=nil
all(:xpath, "//tbody/tr").each do |tr|
#puts "line: #{tr.text}"
if first.nil?
first=tr.text
end
last=tr.text
end
if first =~ /(.+)/
first = $1.split
#puts "first: #{first}"
end
# 1(txid) 2(blocknum) 3(datetime) 4(Received) 5(addresses addr addr) 6(amount)
if last =~ /([0-9a-f]{10})\.\.\. (Block \d+) \(\d{4}-\d+-\d+ \d\d:\d\d:\d\d\) (\d+\.\d+) (Sent|Received): Address ((?:(?:[0-9a-zA-Z]{34}) )+)(\d+\.?\d*)/
out ="#{first[0]} #{$1}\n"
out+="#{first[1]} #{$2}\n"
out+="#{first[2]} #{$3}\n"
out+="#{first[3]} #{$4}\n"
out+="#{first[4]} #{$5}\n"
out+="#{first[5]} #{$6}"
else
puts "last (did not match): #{last}"
end
#puts "latest_transaction: (done)"
#puts out
out
end
def bitcoins(addr)
begin
visit("/address/#{addr}")
rescue
puts page.body
end
latest_transaction
end
end
end
end
end
class BlockChain
def self::dbi_already(amt)
DBI.connect('DBI:SQLite3:blockchain.sqlite', 'ruby', 'ruby') do |dbh|
sql = "SELECT balance FROM latest_balance ORDER BY id DESC LIMIT 1"
row = dbh.select_one(sql)
#puts row[0]
#puts amt==row[0]
if row
amt==row[0]
else
false
end
end
end
def self::dbi_submit(amt)
DBI.connect('DBI:SQLite3:blockchain.sqlite', 'ruby', 'ruby') do |dbh|
sql = "INSERT INTO latest_balance (balance) VALUES (?)"
row = dbh.do(sql, amt)
row==1
end
end
def self::main
#puts "Testing BlockExplorer"
scraper = EAR::Client::BlockExplorer::Tester.new
out = scraper.bitcoins('19bCjfcxrdEyPNoH6rxRhYGaRfmJ4yU3ND')
#puts out # if @debug
if out =~ /Amount\? (.+)/
#puts "Amount: #{$1}"
end
if out =~ /Balance\? (.+)/
bee = Beeminder::User.new "SecretBeeminderAPIkey"
# insert into latest_balance (balance) values (15.62305247);
balance=$1
if !dbi_already(balance)
puts "Posting latest balance: #{balance}"
bee.send "christmas-bitcoins", balance
puts "WARN: Did not enter any update to sqlite" unless dbi_submit(balance)
else
puts "christmas-bitcoins: #{balance}"
end
else
puts "FAIL: Did not get Balance from BlockExplorer"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment