Skip to content

Instantly share code, notes, and snippets.

@aoisensi
Forked from pnlybubbles/bot.rb
Created April 30, 2013 06:22
Show Gist options
  • Save aoisensi/5486923 to your computer and use it in GitHub Desktop.
Save aoisensi/5486923 to your computer and use it in GitHub Desktop.
# encoding: utf-8
require "net/https"
require "oauth"
require "cgi"
require "json"
require "openssl"
require "date"
require "./key_token.rb"
require "pp"
module App
class TwitterAPI
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
# userstream connect method
def connect(&block)
uri = URI.parse("https://userstream.twitter.com/1.1/user.json")
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_mode = OpenSSL::SSL::VERIFY_NONE
# 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
block.call(status)
end
end
end
end
end
# post method
def post(text, *id)
if(id.empty?)
@access_token.post('/statuses/update.json',
'status' => text)
else
@access_token.post('/statuses/update.json',
'status' => text,
'in_reply_to_status_id' => id[0].to_s)
end
end
# favorite method
def favorite(id)
@access_token.post("/favorites/create.json", 'id' => id.to_s)
end
# unfavorite method
def unfavorite(id)
@access_token.post("/favorites/destroy.json", 'id' => id.to_s)
end
# retweet method
def retweet(id)
@access_token.post("/statuses/retweet/#{id}.json")
end
# destroy method
def delete(id)
@access_token.post("/statuses/destroy/#{id}.json")
end
# verify method
def verify_credentials
return JSON.parse(@access_token.get("/account/verify_credentials.json").body)
end
end
class Bot
def initialize
@twitter_api = App::TwitterAPI.new
@my_data = @twitter_api.verify_credentials
@on_text_opt = {:include_mine => true, :include_retweet => true}
@on_reply_opt = {:include_mine => true}
@on_retweet_opt = {:include_mine => true}
@on_delete_opt = {:include_mine => false}
@on_follow_opt = {:include_mine => false}
@on_unfollow_opt = {:include_block => false}
@on_favorite_opt = {:include_mine => false}
@on_unfavorite_opt = {:include_mine => false}
end
def run
loop {
begin
say("Connecting...")
@twitter_api.connect { |res|
check_res(res)
}
rescue Exception => e
if e.to_s == ""
say("Quit.")
exit 1
end
say("ERROR: #{e}", "e")
# puts e.backtrace
end
}
end
# include_mine, include_retweet
def on_text(*options, &block)
@on_text_block = block if block
@on_text_opt = options[0] if !options.empty?
end
# include_mine
def on_reply(*options, &block)
@on_reply_block = block if block
@on_reply_opt = options[0] if !options.empty?
end
# include_mine
def on_retweet(*options, &block)
@on_retweet_block = block if block
@on_retweet_opt = options[0] if !options.empty?
end
# include_mine
def on_delete(*options, &block)
@on_delete_block = block if block
@on_delete_opt = options[0] if !options.empty?
end
# include_mine
def on_follow(*options, &block)
@on_follow_block = block if block
@on_follow_opt = options[0] if !options.empty?
end
# include_block
def on_unfollow(&block)
@on_unfollow_block = block if block
@on_unfollow_opt = options[0] if !options.empty?
end
def on_block(&block)
@on_block_block = block if block
end
# include_mine
def on_unfavorite(*options, &block)
@on_unfavorite_block = block if block
@on_unfavorite_opt = options[0] if !options.empty?
end
# include_mine
def on_favorite(*options, &block)
@on_favorite_block = block if block
@on_favorite_opt = options[0] if !options.empty?
end
def check_res(res)
block = []
case
when res['text']
if res['retweeted_status']
case
when !@on_retweet_opt[:include_mine] && res['source']['id'] == @my_data['id']
else
block << @on_retweet_block if @on_retweet_block
end
else
if res['entities']['user_mentions'].inject([]){ |r, v| r << (v['id'] == @my_data['id']) }.index(true)
case
when !@on_reply_opt[:include_mine] && res['user']['id'] == @my_data['id']
else
block << @on_reply_block if @on_reply_block
end
end
end
case
when !@on_text_opt[:include_retweet] && res['retweeted_status']
when !@on_text_opt[:include_mine] && res['user']['id'] == @my_data['id']
else
block << @on_text_block if @on_text_block
end
when res['delete']
case
when !@on_delete_opt[:include_mine] && res['delete']['status']['user_id'] == @my_data['id']
else
block << @on_delete_block if @on_delete_block
end
when res['friends']
when res['event']
case res['event']
when 'follow'
case
when !@on_follow_opt[:include_mine] && res['source']['id'] == @my_data['id']
else
block << @on_follow_block if @on_follow_block
end
when 'unfollow'
if res['source']['following'] == nil
block << @on_block_block if @on_block_block
end
case
when !@on_unfollow_opt[:include_block] && res['source']['following'] == nil
else
block << @on_unfollow_block if @on_unfollow_block
end
when 'favorite'
case
when !@on_favorite_opt[:include_mine] && res['source']['id'] == @my_data['id']
else
block << @on_favorite_block if @on_favorite_block
end
when 'unfavorite'
case
when !@on_unfavorite_opt[:include_mine] && res['source']['id'] == @my_data['id']
else
block << @on_unfavorite_block if @on_unfavorite_block
end
else
end
else
end
unless block.empty?
block.each { |b| b.call(res, @twitter_api, @my_data) }
end
end
end
end
def say(text, *level)
level_num = "36"
unless level.empty?
case level[0]
when "n"
level_num = "36"
when "e"
level_num = "33"
when "w"
level_num = "31"
end
end
system("echo \"\033[1;#{level_num}m===>\033[0;39m \033[1m#{text}\033[0;39m\"")
end
# encoding: utf-8
require "./bot.rb"
# botを新規作成
bot = App::Bot.new
# あんふぁぼされた時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_unfavorite({:include_mine => false}) { |res, twitter_api| # resはユーザーストリームから取得したハッシュが格納されている、twitter_apiはTwitterAPIにアクセスするためのメソッド群が含まれる
say("Caught Unfavorite.") # sayメソッドでターミナルの標準出力を行える。デフォの出力記号は青色
begin
twitter_api.post("@#{res['source']['id']} #{@mita_text}") # Twitterにポストする
rescue Exception => e
say("POST ERROR: #{e}", "e") # ツイートに失敗した時にエラーを出力する
end
}
# ツイートを取得した時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
# オプションでリツイートを含めるか否かを 選択可能
bot.on_text({:include_mine => true, :include_retweet => true}) { |res, twitter_api|
puts "#{res['created_at']} #{res['user']['screen_name']}: #{res['text']}" # 取得したツイートを標準出力する
if res['text'] =~ /あわあわ/ # エゴサを行う。ツイートの本文を正規表現でフィルタし、含まれていた場合trueとなる
say("Matched EGOSA.")
begin
twitter_api.favorite(res['id']) # ツイートをふぁぼる
rescue Exception => e
say("FAVORITE ERROR: #{e}", "e") # ふぁぼのエラーを出力する
end
end
}
# リプライを取得した時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_reply({:include_mine => false}) { |res|
say("Get Reply from #{res['user']['screen_name']}") # リプライを受けたことを標準出力する
}
# リツイートを取得した時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_retweet({:include_mine => true}) { |res|
}
# ツイートが削除された時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_delete({:include_mine => false}) {
say("See Delete", "w") # ツイートが削除されたことを標準出力する。なお、sayメソッドのレベルはwarningで色は赤となる
}
# フォローされた時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_follow({:include_mine => false}) { |res, twitter_api, my_data| # my_dataは自分の情報の含むハッシュであり、verify_credentialsで取得したものである
begin
twitter_api.post("@#{my_data['screen_name']} followed from #{res['source']['screen_name']}") # フォローされたことを自分にリプライとして送る
rescue Exception => e
say("POST ERROR: #{e}", "e") # ツイートに失敗した時にエラーを出力する
end
}
# ブロックされた時に呼び出される内容を定義
bot.on_block { |res, twitter_api, my_data|
begin
twitter_api.post("@#{my_data['screen_name']} blocked from #{res['target']['screen_name']}") # ブロックれたことを自分にリプライとして送る
rescue Exception => e
say("POST ERROR: #{e}", "e") # ツイートに失敗した時にエラーを出力する
end
}
# ふぁぼられた時に呼び出される内容を定義
# オプションで自分のツイートを含めるか否かを選択可能
bot.on_favorite({:include_mine => false}) { |res|
say("Favorited from #{res['source']['screen_name']}") # ツイートがふぁぼられたことを標準出力する
}
# 実行
bot.run
# encoding: utf-8
CONSUMER_KEY = "*"
CONSUMER_SECRET = "*"
ACCESS_TOKEN = "*"
ACCESS_TOKEN_SECRET = "*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment