-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.rb
105 lines (92 loc) · 2.24 KB
/
bot.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env ruby
require 'tokyotyrant'
require 'rubygems'
require 'oauth'
require 'pit'
require 'json'
class Bot
include TokyoTyrant
CONFIG_REQUIRED = [
'consumer_key',
'consumer_secret',
'access_token',
'access_token_secret',
'tokyotyrant_hostname',
'tokyotyrant_port'
]
def initialize(username)
@behaviors = {}
@username = username
@access_token = OAuth::AccessToken.new(
OAuth::Consumer.new(
config['consumer_key'],
config['consumer_secret'],
:site => 'http://twitter.com'
),
config['access_token'],
config['access_token_secret']
)
end
def config
@config ||= Pit.get(@username, :require =>
Hash[*CONFIG_REQUIRED.map{|c| [c, "#{c} here"]}.flatten]
)
end
def mentions
json = @access_token.get('http://twitter.com/statuses/mentions.json').body
JSON.parse(json)
end
def reply(proc)
rdb = RDB.new
rdb.open(config['tokyotyrant_hostname'], config['tokyotyrant_port'])
last_reply_id_key = "#{@username}_last_reply_id"
last_reply_id = rdb[last_reply_id_key]
replies = mentions.select do |m|
m['id'] > last_reply_id.to_i
end
return if replies == []
replies.each do |r|
begin
if(reply_text = proc.call(r))
post(proc.call(r), :in_reply_to_status_id => r['id'])
end
rescue LocalJumpError
next nil
end
end
rdb[last_reply_id_key] = replies.first['id']
rdb.close
end
def tweet(proc)
if(status = proc.call)
post(status)
end
end
def hbpost(proc)
if (status = proc.call)
post(status)
end
end
def anond(proc)
if (status = proc.call)
post(status)
end
end
def city_news(proc)
if (status = proc.call)
post(status)
end
end
def post(status, options=nil)
params = {:status => status}
params.merge!(options) if options.class == Hash
@access_token.post('http://twitter.com/statuses/update.json', params)
end
def add_behavior(name, proc=nil)
@behaviors[name] = proc
end
def act!
behavior = ARGV[0].to_sym
method(behavior).call(@behaviors[behavior])
end
end