Skip to content

Instantly share code, notes, and snippets.

@pnlybubbles
Last active December 11, 2015 01:28
Show Gist options
  • Save pnlybubbles/4523338 to your computer and use it in GitHub Desktop.
Save pnlybubbles/4523338 to your computer and use it in GitHub Desktop.
あるふぁーかいくんできたよー。 blacklist.csvでブラックリスト指定。 output.txtに書き出し。
# encoding: utf-8
require 'rubygems'
require 'net/https'
require 'openssl'
require 'oauth'
require 'cgi'
require 'json'
# コンシュマーキーとアクセストークン
CONSUMER_KEY = "*"
CONSUMER_SECRET = "*"
ACCESS_TOKEN = "*"
ACCESS_TOKEN_SECRET = "*"
# SSL証明書のパス
CERTIFICATE_PATH = './userstream.twitter.com.pem'
# UserStreamAPIのurl
USERSTREAM_API_URL = 'https://userstream.twitter.com/1.1/user.json?replies=all'
$DEBUG_ = false
class Account
def initialize
@consumer = OAuth::Consumer.new(
CONSUMER_KEY,
CONSUMER_SECRET,
:site => 'http://api.twitter.com/1.1'
)
@access_token = OAuth::AccessToken.new(
@consumer,
ACCESS_TOKEN,
ACCESS_TOKEN_SECRET
)
end
def connect
uri = URI.parse(USERSTREAM_API_URL)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.ca_file = CERTIFICATE_PATH
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.verify_depth = 5
https.start do |https|
request = Net::HTTP::Get.new(uri.request_uri)
request.oauth!(https, @consumer, @access_token)
buf = ""
https.request(request) do |response|
response.read_body do |chunk|
buf << chunk
while(line = buf[/.*(\r\n)+/m])
begin
buf.sub!(line,"")
line.strip!
status = JSON.parse(line)
rescue
break
end
yield status
end
end
end
end
end
end
class Alphakai
attr_reader :blacklist
def initialize
File.open("./blacklist.csv", "w").close() unless File.exist?("./blacklist.csv")
File.open('./blacklist.csv', 'r') do |io|
@blacklist = io.read.strip.split(',')
end
@account = Account.new
end
def run
loop do
puts "==== connecting..."
begin
@account.connect do |j|
if(j['text'])
puts "@#{j['user']['screen_name']}:#{j['text']}"
text = j['retweeted_status'] ? j['retweeted_status']['text'] : j['text']
alpha_handler = Tools.new(j['user']['screen_name'], text)
alpha_handler.bls = @blacklist
alpha_handler.output
puts "=> #{alpha_handler.filtered}" if $DEBUG_
end
end
rescue Exception => e
puts "#### #{e} ####"
puts e.backtrace if $DEBUG_
break if e.to_s == ""
end
puts "==== connection lost."
end
end
class Tools
attr_reader :text
attr_reader :scrnm
attr_reader :filtered
attr_accessor :bls
@@assign = {
/\n/ => " ",
/(RT|QT).*$/ => "",
/^@[A-Za-z0-9_]+\s?/ => "",
/https?:\/\/.*(?=(\s|\n|$))/ => ""
}
def initialize(screen_name, text)
@text = text
@scrnm = screen_name
@filtered = nil
@bls = []
end
def output
File.open('./output.txt', 'a') do |io|
@filtered = filter(@text)
io.puts("#{@scrnm}:#{@filtered}") if @filtered != ""
end
end
private
def filter(str)
return str.gsub(Regexp.union(@@assign.keys),@@assign).gsub(/#{@bls.join("|")}/,"")
end
end
end
Alphakai.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment